• Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • Email
  • RSS
  • Digg
  • Google Plus

String is an immutable class. A String object cannot be modified once created. Take the following example:

public class Test{
public static void main(String s[]) {
                String s3 = new String("Test");
		s3.replaceAll(s3, "Java");
		System.out.println("s3 = " + s3 +" :String cant be modified from Test to Java");

This proves that String is immutable as the value of s3 is still “Test” and not “Java”. This is a real time example of an immutable class. If you were to declare s3 as StringBuffer the output would be “Java”.

Any modification to a String object will result in a new String object.

String s = "test java";
s.substring(0,4); //modify the String
System.out.println(s); // still prints "test java"
String a = s.substring(0,4); //modify the String and assign it to another String
System.out.println(a); // now prints "test"

This proves that if we try to modify the String it will result in a new String object but the original String remains unaffected. String is a final class. It cannot be subclassed. String objects can be used as keys in a HashMap.

Share and Enjoy