String v.s StringBuilder/StringBuffer

By | March 1, 2016


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 ");
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:


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, 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?

s1 and s2 equal
s1 and s3 equal
s1 and s2 equal
s1 and s3 not equal
s1 and s2 not equal
s1 and s3 equal
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.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.