public class StringHandling {
public static void main(String[] args) {
String a = "Hello World";
Test b = new Test(5);
String c = a;
Test d = b;
System.out.println("String a = " + a);
System.out.println("Test b = " + b.a);
System.out.println("String c = " + c);
System.out.println("Test d = " + d.a);
System.out.println();
System.out.println();
a = "Hello People";
b.a = 15;
System.out.println("String a = " + a);
System.out.println("Test b = " + b.a);
System.out.println("String c = " + c);
System.out.println("Test d = " + d.a);
}
}
输出:
a
和c
不同,b
和d
相同? String
和Test
都是Objects
。
请解释一下常规对象和字符串之间的区别。非常感谢你。
答案 0 :(得分:3)
输出:a和c不同
您已分配' c'后来改变了一个'所以他们是不同的。
和b和d是一样的原因?
您已将b
分配给d
,但您不能替换它们,因此它们仍然指向同一个对象。
答案 1 :(得分:2)
首先a
和c
指向同一个String对象。但随后又有了
a = "Hello People"
a
保存对另一个字符串对象的引用,因此它们是不同的。
Test
实例发生了相反的情况。他们仍然持有对同一个对象的引用。所以你基本上用
b.a = 15