Strings
String objects are immutable, but reference to Strings are not. In addition, because of Strings occupying large amount of a program’s memory, the JMV uses the “String constant pool” – a special area of memory to make more memory. Now we will take into account of a following example below to understand about immutable String objects:
String s1 = "Spring "; String s2 = s1 + "Summer "; s1.concat("Fall "); s2.concat(s1); s1 += "Winter "; System.out.println(s1 + " " + s2);
A question is how may String objects and reference variables were created before the println statement?
Step 1:
String s1 = "Spring "
Step 2:
String s2 = s1 + "Summer "
Step 3:
s1.concat("Fall ");
Step 4:
s2.concat(s1);
Step 5:
s1 += "Winter ";
Output in console:
Spring Winter Spring Summer
As a result, there were two of the eight String objects being not lost as follows: “Spring Winter”, and “Spring Summer”. This is a reason why using of Strings often results in a lot of redundancy for a program.
StringBuilder
StringBuilder, by contrast, are mutable. It means that their value will be changed over and over without having to create a new object. Whenever you are doing a lot of String manipulation, the StringBuilder will be more efficient than the String object.
Remember, the StringBuilder methods are not thread-safe, so they likely tend to run faster than StringBuffer methods.
Consider the following program:
class StringEqual { public static void main(String []args) { String s1 = "hello"; String s2 = new String("hello"); String s3 = "hello"; if(s1 == s2) { System.out.println("s1 and s2 equal"); } else { System.out.println("s1 and s2 not equal"); } if(s1 == s3) { System.out.println("s1 and s3 equal"); } else { System.out.println("s1 and s3 not equal"); } } }
Which one of the following options provides the output of this program when executed?
a)
s1 and s2 equal
s1 and s3 equal
b)
s1 and s2 equal
s1 and s3 not equal
c)
s1 and s2 not equal
s1 and s3 equal
d)
s1 and s2 not equal
s1 and s3 not equal
Tips: JVM sets a constant pool in which it stores all the string constants used in the type. If two references are declared with a constant, then both refer to the same constant object. The == operator checks the similarity of objects itself (and not the values in it). Here, the first comparison is between two distinct objects, so we get s1 and s2 not equal. On the other hand, since references of s1 and s3 refer to the same object, we get s1 and s3 equal.
References:
- Oracle Java Tutorial. Accessed on March 01, 2016, https://docs.oracle.com/javase/tutorial/java/data/strings.html