Thursday, 12 December 2013

String is immutable?

This is one of the most popular String interview question in Java, this question some time may be asked as Why String is final in Java.

There may be many reason for this according to the creator of String in Java but few of my points are as:

1. String pool :- It is a special memory area in heap for storing the String literals. if the instance is already exist in the String constant pool then this new instance is mapped to the already existing instance,If not then a new Java String instance is created and stored in the pool.
There are several way to create an object of String, the only way to use the String Constant pool is using Literals

When the compiler encounters a String literal, it checks the pool to see if an identical String already exists.
Lets take an example

String literal = "techArcher"; 
String one = new String(literal);
String two = "techArcher"; 
System.out.println(literal == two); //true 
System.out.println(one == two); //false

String is immutable means String object cannot be changed lets take another example

public class ImmutableStrings 
 public static void main(String[] args)
 { 
    String start = "Hello"; 
    String end = start.concat(" World!"); 
    System.out.println(end); 
 }
 } 
 // Output Hello World!

Well look at that, the String changed...or did it? In that code, no String object was ever changed. We start by assigning "Hello" to our variable, start. That causes a new String object to be created on the heap and a reference to that object is stored in start. Next, we invoke the method concat(String) on that object. Well, here's the trick, if we look at the API Spec for String, you'll see this in the description of the concat(String) method:

Concatenates the specified string to the end of this string. 

If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Notice the part I've highlighted in bold. When you concatenate one String to another, it doesn't actually change the String object, it simply creates a new one that contains the contents of both of the original Strings, one after the other. That's exactly what we did above. The String object referenced by the local variable start never changed. In fact, if you added the statementSystem.out.println(start); after you invoked the concat method, you would see that start still referenced a String object that contained just "Hello". And just in case you were wondering, the '+' operator does the exact same thing as the concat() method.

Strings really are immutable.

No comments:

Post a Comment