The string is immutable means that we cannot change the object itself, but we can change the reference to the object. The string is made final to not allow others to extend it and destroy its immutability.
public class StringImmutableDemo { public static void main(String[] args) { String st1 = "Tutorials"; String st2 = "Point"; System.out.println("The hascode of st1 = " + st1.hashCode()); System.out.println("The hascode of st2 = " + st2.hashCode()); st1 = st1 + st2; System.out.println("The Hashcode after st1 is changed : "+ st1.hashCode()); } }
The hascode of st1 = -594386763 The hascode of st2 = 77292912 The Hashcode after st1 is changed : 962735579
The above is the detailed content of Why is String class immutable or final in Java?. For more information, please follow other related articles on the PHP Chinese website!