If there has to be done lots of string manipulations, using String class would be a waste of memory since String class is immutable there would be lots of abandoned string objects in the string pool when manipulations are being done.
StringBuffer and StringBuilder Classes would handle such manipulations with efficient use of memory because these classes are not immutable and can reuse the same memory over and over. A common use of these classes is IO operations.
StringBuilder was added in Java 5. It has the same methods as the StringBuffer has but its methods are not synchronized and so it is not thread safe. So it runs faster than StringBuffer.
Archive for Strings I/O Formatting and Parsing
The StringBuffer and StringBuilder Classes
Some Facts about String
Once you have assigned a String a value, that value can never change— it’s immutable
To protect the immutability, String class is marked as final. Nobody can override the behaviours of any of the String methods.
To make Java more memory efficient, the JVM sets aside a special area of memory called the “String constant pool” When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.)
What is the output of the code below? How many String objects and how many reference variables were created prior to the println statement?
String s1 = “spring “;
String s2 = s1 + “summer “;
s1.concat(“fall “);
s2.concat(s1);
s1 += “winter “;
System.out.println(s1 + ” ” + s2);
The result of this code fragment is “spring winter spring summer”. There are two reference variables, s1 and s2. There are total of eight String objects created as follows: “spring”, “summer ” (lost), “spring summer”, “fall” (lost), “spring fall” (lost), “spring summer spring” (lost), “winter” (lost), “spring winter” (at this point “spring” is lost). Only two of the eight String objects are not lost in this process.
What is the difference between the below methods of creating a String?
String s=”one”;
String ss=new String(“one”);
First one creates one String object (which is kept in the String constant pool.) and one reference variable.
Second one creates two objects and one reference variable.