Java String变量设置 - 引用还是值? [英] Java String variable setting - reference or value?

查看:136
本文介绍了Java String变量设置 - 引用还是值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following Java code segment is from an AP Computer Science practice exam.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

此代码的输出是BlueJ上的abc ab。但是,其中一个可能的答案选择是abc abc。答案可以取决于Java是否像原始类型(按值)或类似对象(通过引用)设置字符串引用。

The output of this code is "abc ab" on BlueJ. However, one of the possible answer choices is "abc abc". The answer can be either depending on whether Java sets String reference like primitive types (by value) or like Objects (by reference).

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

To further illustrate this, let's look at an example with primitive types:

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

System.out.println(s1 + " " + s2); // prints "1 42"

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

But, say we had BankAccount objects that hold balances.

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() + " " + s2.getBalance()); // prints "0 0"

我不确定Strings的情况如何。它们在技术上是对象,但我的编译器似乎在将变量设置为彼此时将它们视为原始类型。

I'm not sure which is the case with Strings. They are technically Objects, but my compiler seems to treat them like primitive types when setting variables to each other.

如果Java传递String变量(如原始类型),答案是abc ab。但是,如果Java将String变量视为对任何其他Object的引用,则答案为abc abc

If Java passes String variables like primitive type, the answer is "abc ab". However, if Java treats String variables like references to any other Object, the answer would be "abc abc"

您认为哪个是正确答案?

Which do you think is the correct answer?

推荐答案

java字符串是不可变的,因此您的重新分配实际上会导致您的变量指向String的新实例,而不是更改String的值。

java Strings are immutable, so your reassignment actually causes your variable to point to a new instance of String rather than changing the value of the String.

String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

第2行的

,s1 == s2 AND s1.equals(s2)。在第3行连接之后,s1现在引用具有不可变值abc的不同实例,因此s1 == s2和s1.equals(s2)都不是。

on line 2, s1 == s2 AND s1.equals(s2). After your concatenation on line 3, s1 now references a different instance with the immutable value of "abc", so neither s1==s2 nor s1.equals(s2).

这篇关于Java String变量设置 - 引用还是值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆