验证Java的String创建对象以及比较对象
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
System.out.println("s1 == s2:-----:" + (s1 == s2));
System.out.println("s1 == s3:-----:" + (s1 == s3));
System.out.println("s1 == s3.intern():-----:" + (s1 == s3.intern()));
}
Console:
s1 == s2:-----:true
s1 == s3:-----:false
s1 == s3.intern():-----:true
1、String创建对象
Stirng创建对象存在常量池。
jdk1.6及以前版本的运行时常量池在方法区中,jdk1.7及以后版本的运行时常量池在堆中。
String s1 = "abc";
String s2 = "abc";
使用new()创建的对象存在在堆中。
String s3 = new String("abc");
2、String比较对象
s1,s2存在方法区的常量池中,所以 s1 == s2 为 true。
s3存在堆中,所以 s1 == s3 为 false。
字符串s调用intern时,如果常量池中有对象t满足t.equals(s)==true,则返回t的地址;否则,将s的引用(即地址)加入常量池并返回s的引用。所以 s1 == s3.intern() 为 false。