For every change it will occupy separate memory. so Strings are immutable where as StringBuffer is mutable bcoz for every change it wil modify the same memory location
To prove that they are immutable you have to realise two things:1) There are no methods in String that allow it to be manipulated like for example StringBuilder has i.e. append()2) Even if you use the concatenation operator you get a new string as a result. So when you run the following code:
String str = "Hello";
String str2 = str;
str = str + " World";
System.out.println(str2);
System.out.println(str);
You get the following output:
Hello
Hello World
Explanation:
Initially str and str2 both pointed to same object containing the value "Hello". Now when we executed the following:
str = str + " World";
The object with value was unchanged and a new object was created with value "Hello World" and was assigned to str. But str2 still referred to the object containing the value "Hello"
Thus the String is an immutable object.