小编ian*_*avy的帖子

Java字符串变量设置 - 引用还是值?

以下Java代码段来自AP计算机科学实践考试.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);
Run Code Online (Sandbox Code Playgroud)

此代码的输出是BlueJ上的"abc ab".但是,其中一个可能的答案选择是"abc abc".答案可以取决于Java是否将String引用设置为基本类型(按值)或类似对象(通过引用).

为了进一步说明这一点,让我们看一下原始类型的例子:

int s1 = 1;
int s2 = s1; // copies value, not reference
s1 = 42;

System.out.println(s1 + " " + s2); // prints "1 42"
Run Code Online (Sandbox Code Playgroud)

但是,假设我们有持有余额的BankAccount 对象.

BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
BankAccount b2 = b1; // reference to the same object
b1.setBalance(0);
System.out.println(b1.getBalance() + " " + …
Run Code Online (Sandbox Code Playgroud)

java string variables reference

17
推荐指数
6
解决办法
6万
查看次数

标签 统计

java ×1

reference ×1

string ×1

variables ×1