Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

class Testimmutablestring {
	public static void main(String args[]) {
		String s = "Mithilesh";
		s.concat("Kushwaha");// concat() method appends the string at the end
		System.out.println(s);// will print Sachin because strings are immutable
								// objects
	}
} 

But if we explicitely assign it to the reference variable, it will refer to "Rahul Singh" object.For example:

 class Testimmutablestring1{  
 public static void main(String args[]){  
   String s="Mithilesh";  
   s=s.concat(" Kushwaha");  
   System.out.println(s);  
 }  
}  

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 4 reference variables,all referes to one object "rahul".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.