Consider the following example.
String str = new String();
str = \"Hello\";
System.out.println(str); //Prints Hello
str = \"Help!\";
System.out.println(s
String in Java in Immutable and Final just mean it can't be changed or modified:
Case 1:
class TestClass{
public static void main(String args[]){
String str = "ABC";
str.concat("DEF");
System.out.println(str);
}
}
Output: ABC
Reason: The object reference str is not changed in fact a new object "DEF" is created which is in the pool and have no reference at all (i.e lost).
Case 2:
class TestClass{
public static void main(String args[]){
String str="ABC";
str=str.concat("DEF");
System.out.println(str);
}
}
Output: ABCDEF
Reason: In this case str is now referring to a new object "ABCDEF" hence it prints ABCDEF i.e. previous str object "ABC" is lost in pool with no reference.