前言:本文解决的问题
- String的存储在哪里
- 如何判断连个String是否相等==
1.概念介绍:
JAVA中的String是Unicode字符类型,语法上用”“半角双引号引用起。它是不可以改变的,String类也没有提供可以修改字符串的方法。
系统为了提高使用效率,把字符串存储在公共的存储池中;而在栈(stack)中的字符串变量则指向存储池中相应位置。字符串一旦经过更改或进行过其它操作,其实在堆中会创建一个新的对象。
(Strings are immutable, meaning that each time you do something with a string, another object is actually created on the heap. For strings, Java manages a string pool in memory. This means that Java stores and reuse strings whenever possible. )
2.例子说明:
2.1代码说明
public class StringMemoryTest {
public static void main(String[] args) {
//string存在Pool里面
String s1="123";
String s2="123";
System.out.println(s1==s2?true:false);
String s3="1"+"23";
System.out.println(s1==s3?true:false);
/*Strings are immutable, meaning that each time
* you do something with a string,
*another object is actually created on the heap.
*/
String s4 = new Integer(123).toString();
System.out.println(s1==s4?true:false);
String s5 = new String("123");
System.out.println(s1==s5?true:false);
String s7 = new String("123");
System.out.println(s5==s7?true:false);
String s6 = new String("123").intern();
System.out.println(s1==s6?true:false);
}
}
2.1运行结果
true //1
true //2
false //3
false //4
false //5
true //6
3.结果分析:
3.1
String s1="123";
String s2="123";
System.out.println(s1==s2?true:false);
字符串123存在常量池中,s1 s2分别引用它(s1和s2里面存了字符串的地址),因此判断相等。
3.2
String s3="1"+"23";
System.out.println(s1==s3?true:false);
“1”+“2”得到字符串”123”,常量池中已经有“123”了,不需要新建,把s3也指向它;因此判断后输出true。
3.3
String s4 = new Integer(123).toString();
System.out.println(s1==s4?true:false);
前面提到过(meaning that each time you do something with a string, another object is actually created on the heap)每次堆字符串作操作时其实是产生一个新的字符串,这里在堆中新建了对象,s4指向它,s4和s1指向的不是同一个对象,因此判断为false.
3.4
String s5 = new String("123");
System.out.println(s1==s5?true:false);
false;新建了个对象,s5和s1引用值不同。
3.5
String s7 = new String("123");
System.out.println(s5==s7?true:false);
false;新建了个对象,s7和s5引用值不同。
3.6
String s6 = new String("123").intern();
System.out.println(s1==s6?true:false);
true;String.intern()强制告诉JVM把该字符串放到字符串池中,因为原来已经有“123”了,所以直接把引用值返回给s6.
4.总结
JAVA中的String是常量型,不可更改,一旦有所操作其实是在堆中新建了对象。对于比较短的字符串,销毁再建立花费也不大;一旦字符串很长,后续经常更改,建议使用StringBuilder。