Saturday, 28 January 2017

Understanding the immutable nature of java.lang.String

public class ImmutableStringDemo {

public static void main(String[] args) {

String sl = "First Name";  // a string literal
String so = new String("First Name"); // a string object
StringBuffer sb = new StringBuffer("First Name"); // a stringBuffer object


System.out.println("s1 = " + sl + " hashCode = "+ mimicObjectToString(sl));
sl += "Kumar"; // appended ,
System.out.println("s1 = " + sl + " hashCode = "+ mimicObjectToString(sl)+ "\n");
// if the output differs it means a new reference has been created during appending

System.out.println("so = " + so + " hashCode = "+ mimicObjectToString(so));
so += "Kumar";
System.out.println("so = " + so + " hashCode = "+ mimicObjectToString(so)+ "\n");

System.out.println("sb = " + sb + " hashCode = "+ mimicObjectToString(sb));
sb.append("Kumar");
System.out.println("sb = " + sb + " hashCode = "+ mimicObjectToString(sb)+ "\n");

System.out.println("Changed hashCode denotes different reference has been created, making it \"immutable\"");
}

public static String mimicObjectToString(Object o)
    {
        //prevent a NullPointerException by returning null if o is null
        String result = null;
        if (o !=null)
        {
            result = o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
        }
        return  result;
    }
}
 
Click here for running code : https://ideone.com/llyFaU  

Oracle docs defines StringBuffer as "A thread-safe, mutable sequence of characters"

No comments:

Post a Comment