字符串是不可变的意味着我们无法更改对象本身,但我们可以更改对象的引用。该字符串被设置为最终字符串,不允许其他人扩展它并破坏其不变性。
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
以上是为什么在Java中String类是不可变的或者是final的?的详细内容。更多信息请关注PHP中文网其他相关文章!