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

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

问题描述

以下 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"

我不确定字符串是什么情况.它们在技术上是对象,但我的编译器在相互设置变量时似乎将它们视为原始类型.

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 变量视为对任何其他对象的引用,那么答案将是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 字符串变量设置 - 引用还是值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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