All about "String" class In Java

Discussion in 'Java' started by techgeek.in, May 26, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in

    Introduction



    As we already know the primitive data type char represents a character. A chain of characters is called a string. The capability to handle strings is an important feature of any programming language. In Java, each character in a string is a 16-bit Unicode character.Because Unicode characters are 16 bits (not the 7 or 8 bits that ASCII provides), a rich, international set of characters is easily represented in Unicode. In Java, strings are objects. Java offers a final class java.lang.String, which handles strings. In this article I will explore how to use the String class offered by Java to handle strings.

    Constructing Strings with the String Class



    There are several ways to construct a string, an object of String. To start with, let's assume we want to chain together three characters, I, 4, and U. We can do it by using an array of characters, as shown below:

    Code:
    char chara[] = {'I', '4', 'U'};
    
    But this is an array, and although each character in the array is related to other characters, each character is a separate data element. We can convert this array of characters into one data item of type String by passing the char array as an argument to the String constructor:

    Code:
    String str = new String(chara);
    
    Equivalently, we could have passed in a literal value for the string:

    Code:
    String str = new String("I4U");
    
    This line of code creates a new object of class String with a value of "I4U", and assigns it to the reference variable str.
    We can also create a string without the new operator:

    Code:
    String str = "I4U";
    
    There are some subtle differences between these options that we'll discuss later, but what they have in common is that they all create a new String object, with a value of "I4U", and assign it to a reference variable str.

    Finally, we can also create a string by adding two (or more) literals together:

    Code:
    String str = "I4U" + "U4I";
    
    or equivalently:

    Code:
    String str = new String("I4U" + "U4I");
    
    In both cases the string I4UU4I will be created and assigned to the variable str. You can see that the + operator is overloaded here. Java does not allow operator overloading. However, it provides special support for this string concatenation operator (+), and for conversion of other variables to strings. For example, the following is a valid code fragment:

    Code:
    double d = 12.34;
    String str = "I4U"+d;
    
    The value of d is transparently converted to a string and concatenated to the literal string I4U. The variable str now refers to the string I4U12.34.
    Note that when the compiler sees a literal string, it creates and puts it into the pool, and if it sees the same literal string again, it uses the one already in the pool (which is not a thread-safe thing to do, because more than two reference variables can refer to the same string). However, if the same literal string appears in a new statement, that string will be created again at runtime and hence a duplicate of the same string will exist.
    All these different methods for constructing strings are used in the program StringGenerator.java below:

    StringGenerator.java

    Code:
    public class StringGenerator
      {
        public static void main(String[] args)
          {
             char[] chara = {'I','4','U'};
             String s1 = new String(chara);
             String s2 = new String("I4U");
             String s3 = "I4U";
             String s4 = "I4U";
             String s23 = new String("I4U" + "U4I");
             String s32 = "I4U" + "U4I";
             double d = 12.34;
             String s123 = "I4U" + d;
             System.out.println("s1:" + s1 + " s2:" + s2 + "s3:" + s3);
             System.out.println("s23:" + s23 + " s32:" + s32);
             System.out.println("s123:" + s123);
          }
       }
    
    The output is as shown below:

    s1: I4U s2:I4U s3:I4U
    s23:I4UU4I s32:I4UU4I
    s123: I4U12.34

    Methods of the String Class



    The String class offers a wide spectrum of methods to handle strings in an application. We can use these methods to perform operations on a string, including the following:


    • Concatenate a string to another string
    • Examine individual characters of the string
    • Compare strings
    • Search for a character or substrings in a string
    • Extract a substring from a string
    • Create a copy of a string with all characters uppercased
    • Create a copy of a string with all characters lowercased

    Some of the methods of the Class String (All Methods Are Public) are shown below:

    • public char charAt(int index)

      This method returns the character located at the String's specified index. String indexes are zero-based.
      For example,

      Code:
      String x = "airplane";
      System.out.println( x.charAt(2) );       //  output is 'r'
      
    • public String concat(String s)

      This method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke the method.
      For example,

      Code:
      String x = "taxi";
      System.out.println( x.concat(" cab") ); // output is "taxi cab"
      
      The overloaded + operator perform functions similar to the concat() method.
      for example,

      Code:
      String x = "library";
      System.out.println( x + " card");    // output is "library card"
      
    • public boolean equals(String s)

      This method returns a boolean value (true or false) depending on whether the value of the String in the argument is the same as the value of the String used to invoke the method. This method will compare the characters in the Strings casewise.The equals(…) method is inherited from the Object class and is overridden to perform the deep comparison—that is, it compares the characters of the two strings. It returns true if the two strings contain an identical chain of characters. The shallow comparison, which is done in the Object class version of the equals(…) method, simply uses the == operator. It returns true if the two object references are equal—that is, they refer to the same String object.

      For example,

      StringEqual.java

      Code:
      public class StringEqual 
         {
           public static void main(String[] args) 
             {
               String str1 = "Hello Dear!"; 
               String str2 = "Hello Dear!";
               String str3 = new String ("Hello Dear!");
               if (str1.equals(str2)) 
                 {
                   System.out.println("str1 and str2 refer to identical strings.");
                 } 
               else 
                 {
                    System.out.println("str1 and str2 refer to non-identical strings.");
                 }
               if (str1 == str2) 
                 {
                    System.out.println("str1 and str2 refer to the same string.");
                 } 
               else 
                 {
                    System.out.println("str1 and str2 refer to different strings."); 
                 }
               if (str1.equals(str3)) 
                {
                   System.out.println("str1 and str3 refer to identical strings.");
                } 
               else 
                {
                   System.out.println("str1 and str3 refer to non-identical strings.");
                }
              if (str1 == str3) 
                {
                   System.out.println("str1 and str3 refer to the same string.");
                } 
              else 
               {
                   System.out.println("str1 and str3 refer to different strings.");
               }
           } 
        }
      
      The output is as shown below:

      str1 and str2 refer to identical strings.
      str1 and str2 refer to the same string.
      str1 and str3 refer to identical strings.
      str1 and str3 refer to different strings.

    • public boolean equalsIgnoreCase(String s)

      This method performs exactly the same function as the equals() method except that it performs a comparison of the characters in the strings ignoring the case.
      For example,

      Code:
      String x = "Exit";
      System.out.println( x.equalsIgnoreCase("EXIT"));   // is "true"
      System.out.println( x.equalsIgnoreCase("tixe"));   // is "false"
      
    • public int length()

      This method returns the length of the String used to invoke the method.
      For example,

      Code:
      String x = "01234567";
      System.out.println( x.length() );     // returns "8"
      
    • public String replace(char old, char new)

      This method returns a String whose value is that of the String used to invoke the method, updated so that any occurrence of the char in the first argument is replaced by the char in the second argument.
      For example,

      Code:
      String x = "oxoxoxox";
      System.out.println( x.replace('x', 'X') );    // output is "oXoXoXoX"
      
    • public String toLowerCase()

      This method returns a String whose value is the String used to invoke the method, but with any uppercase characters converted to lowercase.
      For example,

      Code:
      String x = "A New Moon";
      System.out.println( x.toLowerCase());    // output is "a new moon"
      
    • public String toUpperCase()

      This method returns a String whose value is the String used to invoke the method, but with any lowercase characters converted to uppercase.
      For eaxmple,

      Code:
      String x = "A New Moon";
      System.out.println( x.toUpperCase());    // output is "A NEW MOON"
      
    • public String trim()

      This method returns a String whose value is the String used to invoke the method, but with any leading or trailing blank spaces removed.
      For example,

      Code:
      String x = "       hi        ";
      System.out.println( x + "x" );             // result is "     hi    x"
      System.out.println( x.trim() + "x");       // result is "hix"
      
    • boolean endsWith(String suffix)

      This method returns true if the current string ends with suffix, else returns false.
      For example,

      Code:
      String x = "Foobar";
      System.out.println( x.endsWith("bar"));    // output is true
      
    • boolean startsWith(String prefix)

      This method returns true if this string starts with the specified prefix.
      For example,

      Code:
      String x = "Foobar";
      System.out.println( x.startsWith("Foo"));    // output is true
      
    • public String substring(int begin), public String substring(int begin, int end)

      This method is used to return a part (or substring) of the String used to invoke the method. The first argument represents the starting location (zero-based) of the substring. If the call has only one argument, the substring returned will include the characters to the end of the original String. If the call has two arguments, the substring returned will end with the character located in the nth position of the original String where n is the second argument. Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last character in the returned String will be in the original String's 7 position, which is index 6.
      For example:

      Code:
      String x = "0123456789";
      System.out.println( x.substring(5) );     // output is  "56789"
      System.out.println( x.substring(5, 8));   // output is "567"
      
    • int compareTo(String str)

      This method makes a lexical comparison. Returns a negative integer if the current string is less than str, 0 if the two strings are identical, and an integer greater than zero if the current string is greater than str.
      For example:

      Code:
      class SortString 
       {
         static String arr[] = {"Now", "is", "the", "time", "for", "all", "good", "men",
      "to", "come", "to", "the", "aid", "of", "their", "country"
                                       };
        public static void main(String args[]) 
          {
              for(int j = 0; j < arr.length; j++) 
                 {
                    for(int i = j + 1; i < arr.length; i++) 
                      {
                         if(arr[i].compareTo(arr[j]) < 0) 
                          { 
                             String t = arr[j];
                             arr[j] = arr[i];
                             arr[i] = t;
                          }
                     }
                    System.out.println(arr[j]);
                }
         }
       }
      
      The output of this program is the list of words:

      Now
      aid
      all
      come
      country
      for
      good
      is
      men
    • int indexOf(int ch)

      This method returns the index within the string of the first appearance of ch.
      For example:

      Code:
      String s = "Sun is shining brightly";
      System.out.println("indexOf(s) = " + s.indexOf('s'));  //output is 5
      
    • int lastIndexOf(int ch)

      This method returns the index within the string of the last appearance of ch.
      For example:

      Code:
      String s = "Sun is shining brightly";
      System.out.println("lastIndexOf(s) = " + s.indexOf('s'));  //output is 7
      


    Immutability Of Strings



    Strings created by using the String class are immutable. Once we have assigned a String a value, that value can never change. However, we can change the reference variable that refers to a string, which means we can make it refer to another string. When you use a method that apparently changes a string and returns the changed string, it is actually a new string that is created and returned; the old string still exists in its unchanged form. So, it appears to you that the string has been changed.
    To understand these concepts, consider the following code fragment:

    Code:
    1.String s = "I4U";
    2.String s1 = s.concat( " and U4I");
    3.s1.toUpperCase();
    
    The execution of line 2 creates a new string and a new reference, s1, that refers to it. The string reference s still refers to the old string. The execution of line 3 creates a new string but no reference variable that would refer to it.

    In the next article I will discuss about the StringBuffer and StringBuilder Class in Java and their comaprison with the String Class.
     
    ankur1337 likes this.
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  3. kcrislyn

    kcrislyn New Member

    Joined:
    Sep 7, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice