小编Rob*_*bin的帖子

String是一个Java中的引用类型?

我理解类是引用类型,例如我创建了以下类:

class Class {

String s = "Hello";

public void change() {
    s = "Bye";
} }
Run Code Online (Sandbox Code Playgroud)

使用以下代码,我理解这Class是一个引用类型:

Class c1 = new Class(); 
Class c2 = c1; //now has the same reference as c1

System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello

c2.change(); //changes s to Bye

System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye
Run Code Online (Sandbox Code Playgroud)

现在我想用String做同样的事情,但这不起作用.我在这做错了什么?:

String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?

System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello

s2 = "Bye"; //now …
Run Code Online (Sandbox Code Playgroud)

java string reference

0
推荐指数
2
解决办法
741
查看次数

标签 统计

java ×1

reference ×1

string ×1