Join Active NET only to learn full-pledged java

Where you can easily download java e-books such as

CORE JAVA, ADVANCED JAVA(JDBC, Servlets, Jsp and Jstl), J2EE, STRUTS, HIBERNATE and SPRING

ANT and log4j

RMI, JNDI and JMS

HTML, CSS, XML and JAVA SCRIPT

OOAD and DESIGN PATTERNS

and many more......................................

Search the web pages from here

String Handling


                                                        
       String Handling


Fundamentals:

ü      In Java a string is a sequence of characters. But, unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String.

ü      When you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you cannot change the characters that comprise (include) that string.

ü      StringBuffer objects contain strings that can be modified after they(strings) are created.

ü      Both the String and StringBuffer classes are defined in java.lang. Thus, they are available to all programs automatically. Both are declared final, which means that neither of these classes may be subclassed.

ü      Beginning with Java 2, version 1.4, both String and StringBuffer implement the CharSequence interface.

ü      To say that the strings within objects of type String are unchangeable means that the contents of the String instance cannot be changed after it has been created. However, a variable declared as a String reference can be changed to point at some other String object at any time.

The String Class and its Constructors:

ü      The String class supports several constructors. To create an empty String, we call the default constructor. For example,

            String s = new String(); will create an instance of String with no characters in it.

ü      If we want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor:

            String(char chars[ ])

      Ex: char chars[] = { 'a', 'b', 'c' };
              String s = new String(chars);
     
      This constructor initializes s with the string “abc”.
      Strings are special variables, they are immutable. After a string has been given an
      assigned string value, it cannot be changed.

ü      We can specify a sub range 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.
     
      Ex: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
            String s = new String(chars, 2, 3);

      This initializes s with the characters cde.

ü      We can construct a String object that contains the same character sequence as another String object using this constructor:
           
           String(String strObj)     Here, strObj is a String object.

Program: Construct one String from another.

            class MakeString
            {
               public static void main(String args[])
               {
                   char c[] = {'J', 'a', 'v', 'a'};
                   String s1 = new String(c);
                   String s2 = new String(s1);
                   System.out.println(s1);
                   System.out.println(s2);
               }
            }
Output: C:\Madhava>javac MakeString.java
               C:\Madhava>java MakeString
               Java
               Java

Program: Construct string from subset of char array.

            class SubString
            {
                public static void main(String args[])
                {
                    byte ascii[] = {65, 66, 67, 68, 69, 70 };
                    String s1 = new String(ascii);
                    System.out.println(s1);
                    String s2 = new String(ascii, 2, 3);
                    System.out.println(s2);
                }
            }
Output: C:\Madhava>javac SubString.java
               C:\Madhava>java SubString
               ABCDEF
               CDE

Note: The contents of the array are copied whenever you create a String object from an array. If you modify the contents of the array after you have created the string, the String will be unchanged.

String Length:

ü      The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here:
            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());

Special String Operations:

String Literals:

ü      Already we know how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal.

ü      For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object.

ü      Ex: The following code fragment creates two equivalent strings:

      char chars[] = { 'a', 'b', 'c' };
      String s1 = new String(chars);
      String s2 = "abc"; // use string literal

      Because a String object is created for every string literal, you can use a string literal
      any place you can use a String object.

String Concatenation:

ü      In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations.
ü      The following fragment concatenates three strings:

      String age = "9";
      String s = "He is " + age + " years old.";
      System.out.println(s);
      This displays the string He is 9 years old.

ü      One practical use of string concatenation is found when we are creating very long strings. Instead of letting long strings wrap around within our source code, we can break them into smaller pieces, using the + to concatenate them.

Program: Using concatenation to prevent long lines.
            class ConCat
            {
               public static void main(String args[])
               {
                  String longStr = "This could have been " + "a very long line that would have "
                  +"wrapped around. But string concatenation " + "prevents this.";
                  System.out.println(longStr);
               }
            }
Output: C:\Madhava>javac ConCat.java
              C:\Madhava>java  ConCat
            This could have been a very long line that would have wrapped around. But string
            concatenation prevents this.

String Concatenation with Other Data Types:

ü      We can concatenate strings with other types of data. For example, consider this slightly different version of the earlier example:
             int age = 9;
             String s = "He is " + age + " years old.";
             System.out.println(s);

      The int value in age is automatically converted into its string representation within a
      String object.

ü      Be careful when you mix other types of operations with string concatenation expressions, however. We might get surprising results. Consider the following:
      String s = "four: " + 2 + 2;
      System.out.println(s);

      This fragment displays
      four: 22
      rather than the
      four: 4
      that we probably expected. Here’s why. Operator precedence causes the
      concatenation of “four” with the string equivalent of 2 to take place first. This result
      is then concatenated with the string equivalent of 2 a second time. To complete the
      integer addition first, you must use parentheses, like this:
     
     String s = "four: " + (2 + 2);
 
     Now s contains the string “four: 4”.

String Conversion and toString( ): 

ü      When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String. valueOf( ) is overloaded for all the simple types and for type Object.  

ü      For the simple types, valueOf( ) returns a string that contains the human-readable equivalent of the value with which it is called.

ü      For objects, valueOf( ) calls the toString( ) method on the object.

ü      Every class implements toString( ) because it is defined by Object.

ü      For most important classes that you create, you will want to override toString( ) and provide your own string representations.

ü      The toString( ) method has this general form:
           
                 String toString( )

ü      By overriding toString( ) for classes that you create, you allow them to be fully integrated into Java’s programming environment.

Program: Override toString() for Box class.
            class Box
            {
                double width;
                double height;
                double depth;
                Box(double w, double h, double d)
                {
                    width = w;
                    height = h;
                    depth = d;
                }
                public String toString()
                {
                   return "Dimensions are " + width + " by " + depth + " by " + height + ".";
                }
            }
            class toStringDemo
            {
                 public static void main(String args[])
                 {
                    Box b = new Box(10, 12, 14);
                    String s = "Box b: " + b; // concatenate Box object
                    System.out.println(b); // convert Box to string
                    System.out.println(s);
                  }
            }

Output: Dimensions are 10.0 by 14.0 by 12.0
               Box b: Dimensions are 10.0 by 14.0 by 12.0

Character Extraction:

ü      The String class provides a number of ways in which characters can be extracted from a String object.

ü      The characters that comprise a string within a String object cannot be indexed as  a character array. Like arrays, the string indexes begin at zero.

charAt( ):

ü      To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.

ü      General form:
                        char charAt(int where)

      Here, where is the index of the character that you want to obtain.The value of where
      must be nonnegative and specify a location within the string. charAt( ) returns the 
      character at the specified location.

ü      For example:
           char ch;
           ch = "abc".charAt(1);
      assigns the value “b” to ch.

getChars( ):

ü      If we need to extract more than one character at a time, we can use the getChars( ) method.

ü      The general form of getChars() is:
      void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

      Here, sourceStart specifies the index of the beginning of the substring, and 
      sourceEnd specifies an index that is one past the end of the desired substring. Thus,  
      the substring contains the characters from sourceStart through sourceEnd–1. The
      array that will  receive the characters is specified by target. The index within target at
      which the substring will be copied is passed in targetStart.

Program: Demonstrates getChars()
            class getCharsDemo
            {
                public static void main(String args[])
                {
                     String s = "This is a demo of the getChars method.";
                     int start = 10;
                     int end = 14;
                     char buf[] = new char[end - start];
                     s.getChars(start, end, buf, 0);
                     System.out.println(buf);
                 }
            }
Output:  demo

getBytes( ):

ü      There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is called getBytes( ), and it uses the default character-to-byte conversions provided by the platform.

ü      Its simplest form is:
            byte[ ] getBytes( )

ü      getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange.

toCharArray( ):

ü      If we want to convert all the characters in a String object into a character array, the
      easiest way is to call toCharArray( ). It returns an array of characters for the entire
      string.

ü      The general form of this one is:
            char[ ] toCharArray( )
    
      This function is provided as a convenience, since it is possible to use getChars( ) to
      achieve the same result.

String Comparison:

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

equals( ) and equalsIgnoreCase( ):

ü      To compare two strings for equality, use equals( ).

ü      It has this general form:
             boolean equals(Object str)
  
      Here, str is the String object being compared with the invoking String object. It  
      returns true if the strings contain the same characters in the same order, and false
      otherwise.
ü      The comparison is case-sensitive.

ü      To perform a comparison that ignores case differences, call equalsIgnoreCase( ).
      When it compares two strings, it considers A-Z to be the same as a-z.

ü      It has this general form:
             boolean equalsIgnoreCase(String str)

      Here, str is the String object being compared with the invoking String object. It,
      too, returns true if the strings contain the same characters in the same order, and
      false otherwise.

Program:  Demonstrate equals() and equalsIgnoreCase().
            class EqualsDemo
            {
                public static void main(String args[])
                {
                   String s1 = "Madhava";
                   String s2 = "Madhava";
                   String s3 = "Ramesh";
                   String s4 = "MADHAVA";
                   System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
                   System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
                   System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
                   System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + 
                                                  s1.equalsIgnoreCase(s4));
                }
            }
Output: C:\Madhava>javac EqualsDemo.java
              C:\Madhava>java EqualsDemo
              Madhava equals Madhava -> true
              Madhava equals Ramesh -> false
              Madhava equals MADHAVA -> false
              Madhava equalsIgnoreCase MADHAVA -> true

regionMatches( ):

ü      The regionMatches( ) method compares a specific region inside a string with another
      specific region in another string. There is an overloaded form that allows us to
      ignore case in such comparisons.

ü      Here are the general forms for these two methods:

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

  boolean regionMatches(boolean ignoreCase, int startIndex, String str2,
                                             int str2StartIndex, int numChars)
ü      In both methods, startIndex specifies the index at which the region begins within the invoking String object. The String being compared is specified by str2. The index at which the comparison will start within str2 is specified by str2StartIndex. The length of the substring being compared is passed in numChars. In the second version, if ignoreCase is true, the case of the characters is ignored. Otherwise, case is significant.

startsWith( ) and endsWith( ):

ü      The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string.

ü      They have the following general forms:
              boolean startsWith(String str)
              boolean endsWith(String str)
      Here, str is the String being tested. If the string matches, true is returned. Otherwise,
      false is returned.

ü      Ex: "Madhav".endsWith("hav") and
            "Madhav".startsWith("Mad")
            are both true.

ü      A second form of startsWith( ), shown here, lets you specify a starting point:
              boolean startsWith(String str, int startIndex)
      Here, startIndex specifies the index into the invoking string at which point the search
      will begin.
ü      For example:
      "Madhav".startsWith("hav", 3) returns true.

equals( ) Versus ==

ü      It is important to understand that the equals( ) method and the == operator perform two different operations.

ü      The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

ü      Program:
      class EqualsNotEqualTo
     {
         public static void main(String args[]) {
         String s1 = "Hello";
         String s2 = new String(s1);
         System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
         System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
         }
      }
ü      Output:  
      The variable s1 refers to the String instance created by “Hello”. The object  referred
      to by s2 is created with s1 as an initializer. Thus, the contents of the two String
      objects are identical, but they are distinct objects. This means that s1 and s2
      do not refer to the same objects and are, therefore, not ==, as is shown here by the
      output of the preceding example:

      Hello equals Hello -> true
      Hello == Hello -> false

compareTo( ):

ü      It is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, 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. The String method compareTo( ) serves this purpose.

ü      It has this general form:
               int compareTo(String str)

      Here, str is the String being compared with the invoking String. The result of the
      comparison is returned and is interpreted as shown here:

                     Value                                           Meaning
              Less than zero                   The invoking string is less than str.
              Greater than zero              The invoking string is greater than str.
              Zero                                  The two strings are equal.

Program: A bubble sort for Strings.
            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]);
                     }
                 }
           }

Output: C:\Madhava>javac SortString.java
              C:\Madhava>java SortString
              Now
              aid
              all
  come
  country
  for
  good
  is
  men
  of
  the
  the
  their
  time
  to
              to

ü      Exp: compareTo( ) takes into account uppercase and lowercase letters. The word “Now” came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set.

ü      If we want to ignore case differences when comparing two strings, use
      compareToIgnoreCase( ):

                    int compareToIgnoreCase(String str)
           
      This method returns the same results as compareTo( ), except that case
      differences are ignored. This method was added by Java 2. We might want to try
      substituting it into the previous program. After doing so, “Now” will no longer be
      first.

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 character or substring was found, or –1 on failure.

ü      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.

ü      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.

ü      We 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)
     
       Here, startIndex specifies the index at which point the search begins. For indexOf( ),
       the search runs from startIndex to the end of the string. For lastIndexOf( ), the
       search runs from startIndex to zero.

Program: Demonstrate indexOf() and lastIndexOf().
class indexOfDemo
{
   public static void main(String args[])
  {
     String s = "Now is the time for all good men " + "to come to the aid of their country.";
     System.out.println(s);
     System.out.println("indexOf(t) = " + s.indexOf('t'));
     System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
     System.out.println("indexOf(the) = " + s.indexOf("the"));
     System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
     System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
     System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60));
     System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
     System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
  }
}
Output: Now is the time for all good men to come to the aid of their country.
               indexOf(t) = 7
   lastIndexOf(t) = 65
   indexOf(the) = 7
   lastIndexOf(the) = 55
   indexOf(t, 10) = 11
   lastIndexOf(t, 60) = 55
   indexOf(the, 10) = 44
   lastIndexOf(the, 60) = 55

Modifying a String:

Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the string with your modifications complete.

substring( ):

ü      We can extract a substring using substring( ).

ü      It has two forms.  The first is
            String substring(int startIndex)

      Here, startIndex specifies the index at which the substring will begin. This form
      returns a copy of the substring that begins at startIndex and runs to the end of the
      invoking string.

ü      The second form of substring( ) allows you to specify both the beginning and  ending index of the substring:
      String substring(int startIndex, int endIndex)

      Here, startIndex specifies the beginning index, and endIndex specifies the stopping
      point. The string returned contains all the characters from the beginning index, up to,
      but not including, the ending index.

Program: Substring replacement.
            class StringReplace
            {
                public static void main(String args[])
                {
                   String org = "This is a test. This is, too.";
                   String search = "is";
                   String sub = "was";
                   String result = "";
                   int i;
                   do   // replace all matching substrings
                   {
                       System.out.println(org);
                       i = org.indexOf(search);
                       if(i != -1)
                       {
                           result = org.substring(0, i);
                           result = result + sub;
                           result = result + org.substring(i + search.length());
                           org = result;
                        }
                     } while(i != -1);
                }
            }
Output: This is a test. This is, too.
   Thwas is a test. This is, too.
   Thwas was a test. This is, too.
   Thwas was a test. Thwas is, too.
   Thwas was a test. Thwas was, too.


concat( ):

ü      We can concatenate two strings using concat( ):

ü      General syntax of concat( ) is:
               String concat(String str)
 
ü      This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +.

ü      For example:
         String s1 = "one";
         String s2 = s1.concat("two");
         puts the string “onetwo” into s2. It generates the same result as the following
         sequence:
         String s1 = "one";
         String s2 = s1 + "two";

replace( ):

ü      The replace( ) method replaces all occurrences of one character in the invoking string
      with another character.

ü      It has the following general form:
      String replace(char original, char replacement)
     
      Here, original specifies the character to be replaced by the character specified by
      replacement. The resulting string is returned.

ü      For example,
         String s = "Hello".replace('l', 'w');
         puts the string “Hewwo” into s.

trim( ):

ü      The trim( ) method returns a copy of the invoking string from which any leading and
      trailing whitespace has been removed.
ü      It has this general form:
         String trim( )

ü      Here is an example:
         String s = " Hello World ".trim();
      This puts the string Hello World into s.

ü      The trim( ) method is useful when you process user commands.

Program: Using trim() to process commands.
            import java.io.*;
            class UseTrim
            {
                public static void main(String args[]) throws IOException
                {
                   // create a BufferedReader using System.in
                   BufferedReader br = new
                   BufferedReader(new InputStreamReader(System.in));
                   String str;
                   System.out.println("Enter 'stop' to quit.");
                   System.out.println("Enter State: ");
                   do
                   {
                      str = br.readLine();
                      str = str.trim(); // remove whitespace
                      if(str.equals("Illinois"))
                         System.out.println("Capital is Springfield.");
                      else if(str.equals("Missouri"))
                          System.out.println("Capital is Jefferson City.");
                      else if(str.equals("California"))
                          System.out.println("Capital is Sacramento.");
                      else if(str.equals("Washington"))
                          System.out.println("Capital is Olympia.");
                      // ...
                    } while(!str.equals("stop"));
                 }
            }

Output: C:\Madhava>javac UseTrim.java
               C:\Madhava>java  UseTrim
               Enter 'stop' to quit.
              Enter State:
               California
               Capital is Sacramento.
               Missouri
               Capital is Jefferson City.

 Data Conversion Using valueOf( ):

ü      The valueOf( ) method converts data from its internal format into a human-readable form. It is a static method that is overloaded within String for all of Java’s built-in types, so that each type can be converted properly into a string.

ü      valueOf( ) is also overloaded for type Object, so an object of any class type you create can also be used as an argument.

ü      static String valueOf(double num)
      static String valueOf(long num)
      static String valueOf(Object ob)
      static String valueOf(char chars[ ])

ü      There is a special version of valueOf( ) that allows you to specify a subset of a char array. It has this general form:

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

Changing the Case of Characters Within a String:

ü      The method toLowerCase( ) converts all the characters in a string from uppercase to
      lowercase.

ü      The toUpperCase( ) method converts all the characters in a string from lowercase to uppercase.

ü      Non-alphabetical characters, such as digits, are unaffected.

ü      The general forms of these methods are,
              String toLowerCase( )
              String toUpperCase( )
      Both methods return a String object that contains the uppercase or lowercase
      equivalent of the invoking String.

Program: Demonstrate toUpperCase() and toLowerCase().
            class ChangeCase
            {
                public static void main(String args[])
                {
                   String s = "Madhava.";
                   System.out.println("Original: " + s);
                   String upper = s.toUpperCase();
                   String lower = s.toLowerCase();
                   System.out.println("Uppercase: " + upper);
                   System.out.println("Lowercase: " + lower);
                }
            }

Output:  Original: Madhava.
               Uppercase: MADHAVA.
               Lowercase: madhava.

StringBuffer:

ü      StringBuffer is a peer class of String that provides much of the functionality of strings.  String represents fixed-length, immutable character sequences.

ü      In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end.

ü      Many programmers deal only with String and let Java manipulate StringBuffers behind the scenes by using the overloaded + operator.

StringBuffer Constructors:

ü      StringBuffer defines these three constructors:
o       StringBuffer( )
o       StringBuffer(int size)
o       StringBuffer(String str)

ü      The default constructor (the one with no parameters) reserves room for 16 characters without reallocation.

ü      The second version (StringBuffer(int size)) accepts an integer argument that explicitly sets the size of the buffer.

ü      The third version ( StringBuffer(String str)) accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.

length( ) and capacity( ):

ü      The current length of a StringBuffer can be found via the length( ) method, while the
      total allocated capacity can be found through the capacity( ) method.

ü      The above two methods have the following general forms:
o       int length( )
o       int capacity( )

Program: StringBuffer length vs. capacity.
            class StringBufferDemo
            {
                 public static void main(String args[])
                 {
                     StringBuffer sb = new StringBuffer("Hello");
                     System.out.println("buffer = " + sb);
                     System.out.println("length = " + sb.length());
                     System.out.println("capacity = " + sb.capacity());
                  }
            }

Here is the output of this program, which shows how StringBuffer reserves extra space for additional manipulations:
      buffer = Hello
      length = 5
      capacity = 21
Since sb is initialized with the string “Hello” when it is created, its length is 5. Its capacity is 21 because room for 16 additional characters is automatically added.

ensureCapacity( ):

ü      If we want to pre-allocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer. ensureCapacity( ) has this general form:

              void ensureCapacity(int capacity)

      Here, capacity specifies the size of the buffer.

setLength( ):

ü      To set the length of the buffer within a StringBuffer object, use setLength( ).

ü      Its general form is : void setLength(int len)

      Here, len specifies the length of the buffer. This value must be nonnegative.

ü      When you increase the size of the buffer, null characters are added to the end of the existing buffer. If you call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.

charAt( ) and setCharAt( ):

ü      The value of a single character can be obtained from a StringBuffer via charAt( ) method.We can set the value of a character within a StringBuffer using setCharAt( )

ü      The general forms are,
         char charAt(int where)
         void setCharAt(int where, char ch)

ü      For charAt( ), where specifies the index of the character being obtained. For setCharAt( ), where specifies the index of the character being set, and ch specifies the new value of that character. For both methods, where must be nonnegative and must not specify a location beyond the end of the buffer.

Program: Demonstrate charAt() and setCharAt().
            class setCharAtDemo
            {
                public static void main(String args[])
                {
                    StringBuffer sb = new StringBuffer("Hello");
                    System.out.println("buffer before = " + sb);
                    System.out.println("charAt(1) before = " + sb.charAt(1));
                    sb.setCharAt(1, 'i');
                    sb.setLength(2);
                    System.out.println("buffer after = " + sb);
                    System.out.println("charAt(1) after = " + sb.charAt(1));
                }
            }
Output: buffer before = Hello
             charAt(1) before = e
             buffer after = Hi
             charAt(1) after = i

getChars( ):

ü      To copy a substring of a StringBuffer into an array, use the getChars( ) method.

ü      It has this general form:
             void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

      Here, sourceStart specifies the index of the beginning of the substring, and sourceEnd
      specifies an index that is one past the end of the desired substring.

ü      The array that will receive the characters is specified by target. The index within target at which the substring will be copied is passed in targetStart.

append( ):

ü      The append( ) method concatenates the string representation of any other type of data
      to the end of the invoking StringBuffer object. It has overloaded versions for all the
      built-in types and for Object.

ü      Here are a few of its forms:
o       StringBuffer append(String str)
o       StringBuffer append(int num)
o       StringBuffer append(Object obj)

ü      String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append( ).

Program: Demonstrate append().
            class appendDemo
            {
                public static void main(String args[])
                {
                   String s;
                   int a = 42;
                   StringBuffer sb = new StringBuffer(40);
                   s = sb.append("a = ").append(a).append("!").toString();
                   System.out.println(s);
                }
            }
Output: a = 42!

insert( ):

ü      The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object.

ü      These are a few of its forms:
o       StringBuffer insert(int index, String str)
o       StringBuffer insert(int index, char ch)
o       StringBuffer insert(int index, Object obj)

Program: The following sample program inserts “like” between “I” and “Java”:
            class insertDemo
            {
                public static void main(String args[])
                {
                    StringBuffer sb = new StringBuffer("J Rao!");
                    sb.insert(2, "Madhava ");
                    System.out.println(sb);
                }
            }
Output: J Madhava Rao!


reverse( ):

ü      We can reverse the characters within a StringBuffer object using reverse( ) method.

ü      It’s general form is,
            StringBuffer reverse( )
    
      This method returns the reversed object on which it was called.

Program: Using reverse() to reverse a StringBuffer.
            class ReverseDemo
            {
                public static void main(String args[])
                {
                    StringBuffer s = new StringBuffer("abcdef");
                    System.out.println(s);
                    s.reverse();
                    System.out.println(s);
                }
            }
Output: abcdef
              fedcba

delete( ) and deleteCharAt( ):

ü      Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and deleteCharAt( ).

ü      Methods:
o       StringBuffer delete(int startIndex, int endIndex)
o       StringBuffer deleteCharAt(int loc)

ü      The delete( ) method deletes a sequence of characters from the invoking object. Here, startIndex specifies the index of the first character to remove, and endIndex  specifies an index one past the last character to remove. Thus, the substring deleted  runs from startIndex to endIndex–1. The resulting StringBuffer object is returned.

ü      The deleteCharAt( ) method deletes the character at the index specified by loc. It returns the resulting StringBuffer object.

Program: Demonstrates the delete( ) and deleteCharAt( ) methods:
            class deleteDemo
            {
                public static void main(String args[])
                {
                   StringBuffer sb = new StringBuffer("This is a test.");
                   sb.delete(4, 7);
                   System.out.println("After delete: " + sb);
                   sb.deleteCharAt(0);
                   System.out.println("After deleteCharAt: " + sb);
                }
            }
Output: After delete: This a test.
               After deleteCharAt: his a test.

replace( ):

ü      Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of
      characters with another set inside a StringBuffer object.

ü      Its signature is,

StringBuffer replace(int startIndex, int endIndex, String str)

      The substring being replaced is specified by the indexes startIndex and endIndex.
      Thus, the substring at startIndex through endIndex–1 is replaced. The replacement
      string is passed in str. The resulting StringBuffer object is returned.

Program: Demonstrates replace( ):
            class replaceDemo
            {
                public static void main(String args[])
                {
                   StringBuffer sb = new StringBuffer("This is a test.");
                   sb.replace(5, 7, "was");
                   System.out.println("After replace: " + sb);
                }
            }

Output: After replace: This was a test.

substring( ):

ü      Java 2 also added the substring( ) method, which returns a portion of a StringBuffer.

ü      Ithas the following two forms:
o       String substring(int startIndex)
o       String substring(int startIndex, int endIndex)

ü      The first form returns the substring that starts at startIndex and runs to the end of the
      invoking StringBuffer object.

ü      The second form returns the substring that starts at startIndex and runs through endIndex–1.

StringBuilder Class

ü      StringBuilder class has been added in jdk1.5 which has same features like StringBuffer class. StringBuilder class objects are also mutable as that are StringBuffer objects. For example, to create objects to StringBuilder class, we can use any one of the following:

·         StringBuilder sb = new StringBuilder(Madhava);
·         StringBuilder sb = new StringBuilder( );
·         StringBuilder sb = new StringBuilder(13);

StringBuilder class methods:

ü      The following are the important methods in StringBuilder class, which are functionally similar to methods of StringBuffer class.

  • StringBuilder append(x)
  • StringBuilder insert(int i, x)
  • StringBuilder delete(int i, int j)
  • StringBuilder reverse()
  • String toString()
  • int length()
  • int indexOf(String str)
  • StringBuilder replace(int i, int j, String str)
  • String substring(int i)
  • String substring(int i, int j) )

ü      The main difference between StringBuffer and StringBuilder classes is that the StringBuffer class is synchronized by default and StringBuilder class is not. This means that, when several threads process or act on a StringBuffer class objects, they are executed one by one on the object, thus ensuring reliable results. But in case of StringBuilder object, since it is not synchronized, it allows several threads to act on it simultaneously. This may lead to inaccurate results in some cases.

ü      Synchronizing the object is like locking the object. This means, when a thread acts on the object, it is locked and any other thread should wait till the current thread completes and unlocks the object. Thus, synchronization does not allow more than 1 thread to act simultaneously on the object.

ü      Implement the synchronization mechanism (like locking and unlocking the object) will take some time for the JVM. Hence StringBuffer class will take more execution time than the StringBuilder class.

Technical Interview Questions and Answers:

1. Is String a class or data type?
Ans: String is a class in java.lang package. But in Java, all classes are also considered as data types. So we can take String as a data type also.

2. Can we call a class as a data type?
Ans: Yes, a class is also called ‘user-defined’ data type. This is because a user can create a class.

3. What is object reference?
Ans: Object reference is a unique hexadecimal number representing the memory address of the object. It is useful to access the members of the object.

4. What is the difference between = = and equals() while comparing strings? Which one is reliable?
Ans:  = = operator compares the references of the string objects. It does not compare the contents of the objects. equals() method compares the contents. While comparing the strings, equals() method should be used as it yields the correct result.

5. What is a String constant pool?
Ans: String constant pool is a separate block of memory where the string objects are held by JVM. If a string object is created directly, using assignment operator as: String s1=Madhava, then it is stored in string constant pool.

6. Explain the difference between the following statements?
            1. String s = Madhava;
            2. String s = new String(Madhava);
Ans: In the first statement, assignment operator is used to assign the string literal to the String variable s. In this case, JVM first of all checks whether the same object is already available in the string constant pool. If it is available, then it creates another reference to it. If the same object is not available, then it creates another object with content Madhava and stores it into the string constant pool.

In the second statement, new operator is used to create the string object. In this case, JVM always creates new object without looking in the string constant pool.

7. What is the difference between String and StringBuffer classes?
Ans: String class objects are immutable and hence their contents can not be modified. StringBuffer class objects are mutable, so they can be modified. Moreover the methods that directly manipulate data of the objects are not available in String class. Such methods are available in StringBuffer class.

8. Are there any other classes whose objects are immutable?
Ans: Yes, classes like Character, Byte, Integer, Float, Double, Long….called wrapper classes are created as immutable. Classes like Class, BigInteger, and BigDecimal are also immutable.

9. What is the difference between StringBuffer and StringBuilder classes?
Ans: StringBuffer class is synchronized and StringBuffer is not. When the programmer wants to use several threads, he should use StringBuffer as it gives reliable results. If only one thread is used, StringBuilder is preferred, as it improves execution time.

10. To what value is a variable of the String type automatically initialized?
Ans: The default value of a String type is null.

11. What is an object’s lock and which objects have locks?
An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.
12. What happens when you add a double value to a String?
Ans: The result is a String object.