Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中通过引用传递。帮我理解_Java_Pass By Reference - Fatal编程技术网

在Java中通过引用传递。帮我理解

在Java中通过引用传递。帮我理解,java,pass-by-reference,Java,Pass By Reference,我有以下代码 public static void main(String[] args) { String word = "Super"; reverseString(word); System.out.println(word); } public static String reverseString(String word) { String helper = ""; int i = word.length() - 1; while (i >= 0) { h

我有以下代码

public static void main(String[] args) {

String word = "Super";

reverseString(word);

System.out.println(word);

}

public static String reverseString(String word) {

String helper = "";

int i = word.length() - 1;

while (i >= 0) {
    helper += word.charAt(i);
    i--;

}

return helper;
我不明白为什么当我打印“word”变量时,它仍然打印“Super”,即使我在reverseString方法中更改了它。我知道字符串是通过引用传递的,而不是像原语值那样的副本

如果我做了
word=reverseString(word)
它会打印出我期望的反面“repuS”


谢谢

您没有在
reverseString
中更改字符串,您正在创建一个新字符串并返回一个新字符串(您称之为
helper


关于Java中的字符串,需要注意的第二件事是它们是不可变的——所有字符串方法都返回一个新字符串,而不是修改调用该方法的字符串

字符串在Java中是不可变的,它的可能副本可能有助于您在引用传递背后的逻辑下