String str1 = "a";
String str2 = "b";
String str3 = "ab";
String str4 = new String("a");
String str5 = new String("b");
String str6= new String("ab");
String plus1 = str1 + str2;
String plus2 = str1 + "b";
String plus3 = str4 + "b";
String plus4 = "a" + "b";
String plus5 = str4 + str5;
String plus6 = str4 + str2;
string相加有上面的6种情况
我想弄清楚各种情况的区别,我知道的是plus4都是在栈区,所以结果是一个字符串常量池里的常量,但是其他情况呢?
另外,我打印plus1~plus6的地址或者hashcode,发现都是一样的,怎么回事?
一楼回答太笼统,而且抛开JVM和JDK版本谈内存分配都是耍流氓。
以提问的为例:
这种直接定义字符串,JVM认为字符串是不变量,也就是线程安全的,因为这种字符串直接分配在方法区的常量池中.
有new关键字,说明这种字符串是分配在堆上.可以使用如下方法验证:
回答一下为什么plus1~6的hashcode一样,是因为你没有去重写String的hashcode方法。而String默认hashcode的实现为:
只是对字面常量做了处理,而plus1~6的字面常量一样,所以hashcode值当然一致。然后hashcode一致,不代表它们在jvm分配的内存地址一致。