SlideShare uma empresa Scribd logo
1 de 38
String classes and its methods




 http://improvejava.blogspot.in
                                  1
Objectives


On completion of this period, you would be able to know

              • String class
              • Methods of String class




                               http://improvejava.blogspot.in
Recap

In C / C++
   •    String is collection of characters
   •    It should be declared like a character array of some size
   •    Every string ends with a null ( ‘0’ ) character
   •    Memory is allocated sequentially because it is array
        eg. :
                   char name[5];
                   strcpy(name,”ramu”);
                            [0] [1] [2] [3]            [4]
                    name ‘r’      ‘a’   ‘m’     ‘u’   ‘0’
                          1000 1001 1002 1003 1004
                         http://improvejava.blogspot.in
                                                                    3
String Class


• String is probably the most commonly used class in java’ class
• Strings are very important part of programming
• Every string you create is actually an object of type String
• Even string constants are actually String objects
• Java language provides a system defined class String in the
  java.lang package



                          http://improvejava.blogspot.in
                                                                   4
String Class                    contd..

• For example: in the statement

  System.out.println(“ this is a string ”);

• The string “ this is a string ” is a String constant

• Java handles String constants in the same way that other computer
  languages handle “normal” strings




                           http://improvejava.blogspot.in
                                                                      5
String Class

• The objects of type Strings are immutable

• Once a String is created, its contents cannot be altered

• This may seem like a serious restriction but we have the following
  advantages with this

   • If you need to change a string, you can always create a new one
     that contains the modifications

   • Java defines a peer class of String, called StringBuffer, which
     allows strings to be altered

                          http://improvejava.blogspot.in
                                                                   6
String Class                 contd..

Strings can be constructed a variety of ways. The easiest is to use a
  statement like this

   String s = “ Good Morning ”;



                                           “Good Morning”
         s


   s is the reference                    Fig 30.1


                         http://improvejava.blogspot.in
                                                                      7
String Class                  contd..

• Once you have created a String object, you can use it anywhere
  that a string is allowed

• For example, this statement displays cname

               System.out.println(cname);

• Java defines ‘+’ operator for String objects


• It is used to concatenate two strings


                          http://improvejava.blogspot.in
                                                                     8
String Class                   contd..



• For example, this statement

     String cname = “ govt ” + “polytechnic” ;

   results in cname containing “govt polytechnic“


• The following program demonstrates the preceding concepts



                         http://improvejava.blogspot.in
                                                                    9
Example Program: String Class
// Demonstrating Strings
class StringDemo {

      public static void main(String args[]) {
        String str1 = “one”;
        String str2 = “two”
        String str3 = str1 + “ and ” + str2’;

         System.out.println(“ str1 ”);
         System.out.println(“ str2”);
         System.out.println(“ str3”);
                                                            Output :
      } // end of main method
                                                                  one
                                                                  two
} // end of class                                                 one and two


                           http://improvejava.blogspot.in
                                                                                10
String Class                    contd..

• String class contains several methods that you can use

   • test two strings for equality by using equals()

              boolean equals(String object);

   • obtain the length of a string by calling the length().

              int length();

   • Obtain the character at a specified index within a string by
     calling charAt()
             char charAT(int index);
                          http://improvejava.blogspot.in
                                                                     11
Example program
class StringDemo2 {
       public static void main(String args[]) {          Output :
               String str1 = “one”;                             length of str1 : 3
                                                                char at index 2: n
               String str2 = “two”;
                                                                str1 != str2
               String str3 = str1;                              str1 == str3
               System.out.println(“ length of str1 : ”+str1.length());
               System.out.println(“ char at index 2 in str1 : ”+str1.charAt(2));
               if(str1.equals(str2)) {
                       System.out.println(“ str1 == str2”);
               else
                       System.out.println(“ str1 != str2”);
               if(str1.equals(str3)) {
                       System.out.println(“ str1 == str3”);
               else
                       System.out.println(“ str1 != str3”);
       }
}
                           http://improvejava.blogspot.in
                                                                                     12
The String Constructors


• To create an empty String, you call the default constructor.
  For example

               String s = new String():

•   will create an instance of String with no characters in it

• String class has also parameterized constructors

• If you want to create strings that have initial values. The string
  class provides a variety of constructors to handle this

                         http://improvejava.blogspot.in
                                                                       13
The String Constructors                         contd..

• To create an empty String initialized by an array of characters,
  use the constructor shown here

               String(char chars[] )

  eg.
               char chars[] = {‘a’, ‘b’, ’c’ };

               String s = new String(chars);

  The constructor initializes s with the string “abc”


                         http://improvejava.blogspot.in
                                                                     14
The String Constructors                    contd..
• You can specify a subrange of a character array as an initializer
  using the following constructor

               String(char chars[] , int startIndex, int numChars)

  here, startIndex specifies the index at which the subrange begins,
  and numChars specifies the number of characters to use
        eg.
                char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’};

               String s = new String(chars,2,3);

               this initializes s with the characters cde
                         http://improvejava.blogspot.in
                                                                       15
The String Constructors                         Contd..
• You can construct a String object that contains the same character
  sequence as another String object using the following constructor

                        String(String strObj)

  here, strObj is a String object
        eg.
               char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’};

                String s1 = new String(chars);

                String s2 = new String(s1);
                String objects s1 and s2 contains same String
                          http://improvejava.blogspot.in
                                                                     16
The String Methods
• String length
   • The length of a string is the number of characters that it
     contains. To obtain this value, call the length() method

              int length()
   • The following fragment prints “3”, since there are three
     characters in the string s;
              char chars[] = {‘ a ’, ‘ b ’, ‘ c ’};
              String s = new String(chars);

              System.out.println(s.length());
                    or
              System.out.println(“abc”.length());
                        http://improvejava.blogspot.in
                                                                  17
The String methods                   Contd..
• toString() :
   • Every class implements toString() because it is defined by
     Object
   • However, the default implementation of toString() is seldom
     sufficient
   • The general form of toString() method is
                     String toString()

  class A {                          class B {
     public String toString() {          public static void main (String
       return “hello”;               args[]) {
   }                                          A a = new A();
  }                                           String s = “hai” + a;
                                              System.out.println(s);
                                         }
                                      }
                         http://improvejava.blogspot.in
                                    CM602.32                               18
The String Methods                          contd..
• Character extraction
   • The String class provides a number of ways in which
     characters can be extracted from a String object.
   • The string index begins at zero

      char charAt() : to extract a single character from a String

                     char ch;
                     ch =“abc”.charAt(1)

             assigns the value “b” to ch


                       http://improvejava.blogspot.in
                                                                    19
The String Methods                             contd..

getChars()
 If you need to extract more than one character at a time, you can
 use the getchars() method, it has this general form

   void getChars(int soureStart, int sourceEnd, char target[], int targetStart)

            String s = “government polytechnic warangal”;
            int start = 10;
            int end = 14;
            char buf[] = new char[end-start];
            s.getShars(start, end,buf,0);
            System.out.println(buf);
                          http://improvejava.blogspot.in
                                                                                  20
The String Methods                         contd..
getBytes()
•    It is alternative to getChars() that stores the characters in an
    array of bytes

             byte[] getBytes()

toCharArray()
•    It returns an array of characters for the entire string

             char[] toCharArray()


                       http://improvejava.blogspot.in
                                                                        21
String Comparison

• The String class includes several methods that compare
  strings or substrings within strings

equals( )
•    two compare two strings for equality, use equals()


            boolean equals(Object str)

•    Here, str is the string object being compared with the invoking
    String object

                       http://improvejava.blogspot.in
                                                                  22
String Comparison                 contd..

equalsIgnoreCase( )
•    To perform a comparison that ignores case differences

             boolean equalsIgnoreCase(String str)

•    when it compares two strings, it considers A – Z to be the same
    as a – z

•    here, str is the String object being compared with the invoking
    String object


                        http://improvejava.blogspot.in
                                                                   23
String comparison                   contd..
class A {
  public static void main(String args[]) {

        String s1 = “hello”;
        String s2 = “hello”;
        String s3 = “HELLO”;

        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
        System.out.println(s1.equalsIgnoreCase(s3));
    }
}

                         http://improvejava.blogspot.in
                                                                    24
String Comparison                    contd..
regionMatches( )
• Compares a specific region inside a string with another specific
  region in another string

• There is an overloaded form that allows you to ignore case in
  such comparison

   boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
  numChars)

   boolean regionMatches(boolean ignoreCase, int startIndex, String str2,
                           int str2StartIndex, int numChars)



                           http://improvejava.blogspot.in
                                                                                25
String Comparison                   contd..
startsWith( )
•    Determines whether a given String begins with a specified
    string

                   boolean startsWith(String str)

             eg:   “Foobar”.startsWith(“Foo”)
endsWith( )
•    Determines whether a given String ends with a specified string

                   boolean endsWith(String str)

             eg:   “Foobar”.startsWith(“Foo”)
                        http://improvejava.blogspot.in
                                                                   26
String Comparison contd..
equals ( ) versus ==
•    equals() methods compares the characters inside a String
    object

      = = operator compares two object references to see whether
    they refer to the same instance
             class A {
                      public static void main(String args[]) {
                                 String s1 = “Hello”;
                                 String s2 = new String(s1);
                                 System.out.println(s1.equals(s2));
                                 System.out.println(s1==s2);
                      }
             }           http://improvejava.blogspot.in
                                                                      27
String Comparison                          contd..

compareTo( )
• Used to know two strings are identical, less than, or greater than
  the next
• A string is less than another if it comes before the other in
  dictionary order
• A string is greater than another if it comes after the other in
  dictionary order
                    int compareTo(String str)
• Here, str is the string being compared with the invoking String




                      http://improvejava.blogspot.in
                                                                  28
Searching Strings
• The String class provides two methods that allow you to search
  a string for a specified character or substring

  indexOf()    - searches for the first occurrence of a character or
  substring.

  lastIndexOf() - searches for the last occurrence of a character or
  substring

• These two methods are overloaded in several different ways. In
  all cases , the methods return the index at which the charcter or
  substring was found or -1 returned on failure

                      http://improvejava.blogspot.in
                                                                   29
Searching Strings                    contd..

• To search for the first occurrence of a character, use

                   int indexOf(int ch)

• To search for the last occurrence of a character, use

                   int lastIndexOf(int ch)

• Here, ch is the character being sought




                      http://improvejava.blogspot.in
                                                            30
Searching Strings                           contd..
• To search for the first or last occurrence of a substring, use

                   int indexOf(String str)
                   int lastIndexOf(String str)

• Here, str specifies the substring

• You can specify a starting point for the search using these forms
                 int indexOf(int ch, int startIndex)
                 int lastIndexOf(int ch, int startIndex)

                   int indexOf(String str, int startIndex)
                   int lastIndexOf(String str, int startIndex)
                       http://improvejava.blogspot.in
                                                                   31
Modifying a String

replace() - replaces all occurrences of one character in the
invoking string

         String replace(char original, char replacement)
         String subString(int startIndex, int endIndex)

trim() - returns a copy of the invoking string from which any
leading and trailing white space has been removed

         String trim()


                    http://improvejava.blogspot.in
                                                                32
Changing the case of characters within a String

  toLowerCase() - converts all the characters in a string from
  uppercase to lowercase

          String toLowerCase()

  toUpperCase() - converts all the characters in a string from
  lowercase to uppercase

          String toUpperCase()




                     http://improvejava.blogspot.in
                                                                 33
Summary



• We discussed
  • String classes
  • Uses of string class
  • Syntax of string class
  • Constructors of String class
  • Methods of String class


                     http://improvejava.blogspot.in
                                                      34
Assignment


1. Write a class that has String types and also that uses
   various String methods to perform operations on the
   above data




                     http://improvejava.blogspot.in
Quiz
1. String are
   a. mutable
   b. immutable
   c. none




             http://improvejava.blogspot.in
                                              36
Quiz                       contd..

2. String is
   a. variable
   b. class
   c. data type
   d. none




                  http://improvejava.blogspot.in
Frequently Asked Questions

1. Explain the use String class

2. Differentiate String and StringBuffer classes

3. Explain various methods in String class with example
   programs



                    http://improvejava.blogspot.in
                                                      38

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java String
Java String Java String
Java String
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Java Strings
Java StringsJava Strings
Java Strings
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
Java input
Java inputJava input
Java input
 
Java String
Java StringJava String
Java String
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
I/O Streams
I/O StreamsI/O Streams
I/O Streams
 
Packages in java
Packages in javaPackages in java
Packages in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 

Semelhante a String classes and its methods.20

Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docxPamarthi Kumar
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learningASIT Education
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
String Operations.pptx
String Operations.pptxString Operations.pptx
String Operations.pptxpateljay401233
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 

Semelhante a String classes and its methods.20 (20)

Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
 
Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Learn c sharp at amc square learning
Learn c sharp at amc square learningLearn c sharp at amc square learning
Learn c sharp at amc square learning
 
String.ppt
String.pptString.ppt
String.ppt
 
String handling
String handlingString handling
String handling
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
String.pptx
String.pptxString.pptx
String.pptx
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
String Operations.pptx
String Operations.pptxString Operations.pptx
String Operations.pptx
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 

Mais de myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

String classes and its methods.20

  • 1. String classes and its methods http://improvejava.blogspot.in 1
  • 2. Objectives On completion of this period, you would be able to know • String class • Methods of String class http://improvejava.blogspot.in
  • 3. Recap In C / C++ • String is collection of characters • It should be declared like a character array of some size • Every string ends with a null ( ‘0’ ) character • Memory is allocated sequentially because it is array eg. : char name[5]; strcpy(name,”ramu”); [0] [1] [2] [3] [4] name ‘r’ ‘a’ ‘m’ ‘u’ ‘0’ 1000 1001 1002 1003 1004 http://improvejava.blogspot.in 3
  • 4. String Class • String is probably the most commonly used class in java’ class • Strings are very important part of programming • Every string you create is actually an object of type String • Even string constants are actually String objects • Java language provides a system defined class String in the java.lang package http://improvejava.blogspot.in 4
  • 5. String Class contd.. • For example: in the statement System.out.println(“ this is a string ”); • The string “ this is a string ” is a String constant • Java handles String constants in the same way that other computer languages handle “normal” strings http://improvejava.blogspot.in 5
  • 6. String Class • The objects of type Strings are immutable • Once a String is created, its contents cannot be altered • This may seem like a serious restriction but we have the following advantages with this • If you need to change a string, you can always create a new one that contains the modifications • Java defines a peer class of String, called StringBuffer, which allows strings to be altered http://improvejava.blogspot.in 6
  • 7. String Class contd.. Strings can be constructed a variety of ways. The easiest is to use a statement like this String s = “ Good Morning ”; “Good Morning” s s is the reference Fig 30.1 http://improvejava.blogspot.in 7
  • 8. String Class contd.. • Once you have created a String object, you can use it anywhere that a string is allowed • For example, this statement displays cname System.out.println(cname); • Java defines ‘+’ operator for String objects • It is used to concatenate two strings http://improvejava.blogspot.in 8
  • 9. String Class contd.. • For example, this statement String cname = “ govt ” + “polytechnic” ; results in cname containing “govt polytechnic“ • The following program demonstrates the preceding concepts http://improvejava.blogspot.in 9
  • 10. Example Program: String Class // Demonstrating Strings class StringDemo { public static void main(String args[]) { String str1 = “one”; String str2 = “two” String str3 = str1 + “ and ” + str2’; System.out.println(“ str1 ”); System.out.println(“ str2”); System.out.println(“ str3”); Output : } // end of main method one two } // end of class one and two http://improvejava.blogspot.in 10
  • 11. String Class contd.. • String class contains several methods that you can use • test two strings for equality by using equals() boolean equals(String object); • obtain the length of a string by calling the length(). int length(); • Obtain the character at a specified index within a string by calling charAt() char charAT(int index); http://improvejava.blogspot.in 11
  • 12. Example program class StringDemo2 { public static void main(String args[]) { Output : String str1 = “one”; length of str1 : 3 char at index 2: n String str2 = “two”; str1 != str2 String str3 = str1; str1 == str3 System.out.println(“ length of str1 : ”+str1.length()); System.out.println(“ char at index 2 in str1 : ”+str1.charAt(2)); if(str1.equals(str2)) { System.out.println(“ str1 == str2”); else System.out.println(“ str1 != str2”); if(str1.equals(str3)) { System.out.println(“ str1 == str3”); else System.out.println(“ str1 != str3”); } } http://improvejava.blogspot.in 12
  • 13. The String Constructors • To create an empty String, you call the default constructor. For example String s = new String(): • will create an instance of String with no characters in it • String class has also parameterized constructors • If you want to create strings that have initial values. The string class provides a variety of constructors to handle this http://improvejava.blogspot.in 13
  • 14. The String Constructors contd.. • To create an empty String initialized by an array of characters, use the constructor shown here String(char chars[] ) eg. char chars[] = {‘a’, ‘b’, ’c’ }; String s = new String(chars); The constructor initializes s with the string “abc” http://improvejava.blogspot.in 14
  • 15. The String Constructors contd.. • You can specify a subrange of a character array as an initializer using the following constructor String(char chars[] , int startIndex, int numChars) here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use eg. char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’}; String s = new String(chars,2,3); this initializes s with the characters cde http://improvejava.blogspot.in 15
  • 16. The String Constructors Contd.. • You can construct a String object that contains the same character sequence as another String object using the following constructor String(String strObj) here, strObj is a String object eg. char chars[] = {‘a’, ‘b’, ’c’ ,’d’, ’e’, ’f’}; String s1 = new String(chars); String s2 = new String(s1); String objects s1 and s2 contains same String http://improvejava.blogspot.in 16
  • 17. The String Methods • String length • The length of a string is the number of characters that it contains. To obtain this value, call the length() method int length() • The following fragment prints “3”, since there are three characters in the string s; char chars[] = {‘ a ’, ‘ b ’, ‘ c ’}; String s = new String(chars); System.out.println(s.length()); or System.out.println(“abc”.length()); http://improvejava.blogspot.in 17
  • 18. The String methods Contd.. • toString() : • Every class implements toString() because it is defined by Object • However, the default implementation of toString() is seldom sufficient • The general form of toString() method is String toString() class A { class B { public String toString() { public static void main (String return “hello”; args[]) { } A a = new A(); } String s = “hai” + a; System.out.println(s); } } http://improvejava.blogspot.in CM602.32 18
  • 19. The String Methods contd.. • Character extraction • The String class provides a number of ways in which characters can be extracted from a String object. • The string index begins at zero char charAt() : to extract a single character from a String char ch; ch =“abc”.charAt(1) assigns the value “b” to ch http://improvejava.blogspot.in 19
  • 20. The String Methods contd.. getChars() If you need to extract more than one character at a time, you can use the getchars() method, it has this general form void getChars(int soureStart, int sourceEnd, char target[], int targetStart) String s = “government polytechnic warangal”; int start = 10; int end = 14; char buf[] = new char[end-start]; s.getShars(start, end,buf,0); System.out.println(buf); http://improvejava.blogspot.in 20
  • 21. The String Methods contd.. getBytes() • It is alternative to getChars() that stores the characters in an array of bytes byte[] getBytes() toCharArray() • It returns an array of characters for the entire string char[] toCharArray() http://improvejava.blogspot.in 21
  • 22. String Comparison • The String class includes several methods that compare strings or substrings within strings equals( ) • two compare two strings for equality, use equals() boolean equals(Object str) • Here, str is the string object being compared with the invoking String object http://improvejava.blogspot.in 22
  • 23. String Comparison contd.. equalsIgnoreCase( ) • To perform a comparison that ignores case differences boolean equalsIgnoreCase(String str) • when it compares two strings, it considers A – Z to be the same as a – z • here, str is the String object being compared with the invoking String object http://improvejava.blogspot.in 23
  • 24. String comparison contd.. class A { public static void main(String args[]) { String s1 = “hello”; String s2 = “hello”; String s3 = “HELLO”; System.out.println(s1.equals(s2)); System.out.println(s1.equals(s3)); System.out.println(s1.equalsIgnoreCase(s3)); } } http://improvejava.blogspot.in 24
  • 25. String Comparison contd.. regionMatches( ) • Compares a specific region inside a string with another specific region in another string • There is an overloaded form that allows you to ignore case in such comparison boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars) http://improvejava.blogspot.in 25
  • 26. String Comparison contd.. startsWith( ) • Determines whether a given String begins with a specified string boolean startsWith(String str) eg: “Foobar”.startsWith(“Foo”) endsWith( ) • Determines whether a given String ends with a specified string boolean endsWith(String str) eg: “Foobar”.startsWith(“Foo”) http://improvejava.blogspot.in 26
  • 27. String Comparison contd.. equals ( ) versus == • equals() methods compares the characters inside a String object = = operator compares two object references to see whether they refer to the same instance class A { public static void main(String args[]) { String s1 = “Hello”; String s2 = new String(s1); System.out.println(s1.equals(s2)); System.out.println(s1==s2); } } http://improvejava.blogspot.in 27
  • 28. String Comparison contd.. compareTo( ) • Used to know two strings are identical, less than, or greater than the next • A string is less than another if it comes before the other in dictionary order • A string is greater than another if it comes after the other in dictionary order int compareTo(String str) • Here, str is the string being compared with the invoking String http://improvejava.blogspot.in 28
  • 29. Searching Strings • The String class provides two methods that allow you to search a string for a specified character or substring indexOf() - searches for the first occurrence of a character or substring. lastIndexOf() - searches for the last occurrence of a character or substring • These two methods are overloaded in several different ways. In all cases , the methods return the index at which the charcter or substring was found or -1 returned on failure http://improvejava.blogspot.in 29
  • 30. Searching Strings contd.. • To search for the first occurrence of a character, use int indexOf(int ch) • To search for the last occurrence of a character, use int lastIndexOf(int ch) • Here, ch is the character being sought http://improvejava.blogspot.in 30
  • 31. Searching Strings contd.. • To search for the first or last occurrence of a substring, use int indexOf(String str) int lastIndexOf(String str) • Here, str specifies the substring • You can specify a starting point for the search using these forms int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) http://improvejava.blogspot.in 31
  • 32. Modifying a String replace() - replaces all occurrences of one character in the invoking string String replace(char original, char replacement) String subString(int startIndex, int endIndex) trim() - returns a copy of the invoking string from which any leading and trailing white space has been removed String trim() http://improvejava.blogspot.in 32
  • 33. Changing the case of characters within a String toLowerCase() - converts all the characters in a string from uppercase to lowercase String toLowerCase() toUpperCase() - converts all the characters in a string from lowercase to uppercase String toUpperCase() http://improvejava.blogspot.in 33
  • 34. Summary • We discussed • String classes • Uses of string class • Syntax of string class • Constructors of String class • Methods of String class http://improvejava.blogspot.in 34
  • 35. Assignment 1. Write a class that has String types and also that uses various String methods to perform operations on the above data http://improvejava.blogspot.in
  • 36. Quiz 1. String are a. mutable b. immutable c. none http://improvejava.blogspot.in 36
  • 37. Quiz contd.. 2. String is a. variable b. class c. data type d. none http://improvejava.blogspot.in
  • 38. Frequently Asked Questions 1. Explain the use String class 2. Differentiate String and StringBuffer classes 3. Explain various methods in String class with example programs http://improvejava.blogspot.in 38