Java-String的值的指向问题

1字符串一旦被创建就不能被修改(图1)

String s = "abc";
s = "qwe";
System.out.println(s)

解释:

  • 并不是把 s 的值进行了修改。而是在常量池中创建了新的地址存放了“qwe”, 然后s 指向“qwe”这个新地址

2

String s = "hello";
s +="world";
System.out.println(s)

常量:先进行拼接,然后再常量池中找。找到了直接给地址值;找不到开辟空间在赋值;

变量:直接进行拼接,然后赋值,再将地址值传给main方法中的引用

3

String s = new String(“hello”);
String s1 = "hello";

s和s1 所指向的地址值不一样。但是最终指向的都是常量池中的"hello”;

posted @ 2022-03-26 13:41  a-tao必须奥利给  阅读(82)  评论(0)    收藏  举报