标签:
In Java, the String will have different usage.
Example:
public class Test {
public static void main(String[] args) {
String s1 = "accp";
String s2 = "accp";
String s3 = new String(s1);
if(s1 == s2) {
System.out.print("true, ");
} else {
System.out.print("false,");
}
if(s1 == s3) {
System.out.println("true");
} else {
System.out.println("false");
}
}
} /* Output:
true, false
*/
对于语句String s1 = "accp";
Java内部将此语句转化为以下几个步骤:
String s1 = "accp";其字符串值是保存了一个指向存在栈中数据的引用!所以s1和s2的引用地址是相同的,所s1==s2为true。
而String s3 = new String(s1);是创建一个对象,也就是创建了新的引用,所以s3的引用地址是新创建的,当然和s1的引用地址不同。所以s1 == s3为false。
==是比较对象的引用地址,如果要比较对象的值的话用equal吧!
标签:
原文地址:http://www.cnblogs.com/kid551/p/4568872.html