为什么我的Java方法不能改变传递的变量? [英] Why can't my Java method change a passed variable?

查看:187
本文介绍了为什么我的Java方法不能改变传递的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到以下代码没有按预期工作时,我感到很困惑。

I was kind of baffled when I saw the following code did not work as expected.

我认为Java总是通过引用传递变量到函数中。因此,为什么函数不能重新分配变量?

I thought Java always passed variables by references into functions. Therefore, why can't the function reassign the variable?

public static void main(String[] args) {

  String nullTest = null;

  setNotNull(nullTest);

  System.out.println(nullTest);
}

private static void setNotNull(String s) {
  s = "not null!";
}

此程序输出 null

推荐答案

对象的引用由Java中的 value 传递,因此分配给局部变量该方法不会更改原始变量。只有局部变量 s 指向一个新字符串。用一点ASCII艺术可能更容易理解。

References to objects are passed by value in Java so assigning to the local variable inside the method doesn't change the original variable. Only the local variable s points to a new string. It might be easier to understand with a little ASCII art.

最初你有这个:

------------
| nullTest |
------------
     |
    null

当你第一次输入方法setNotNull时,你得到一个的副本 s 中nullTest的值。在这种情况下,nullTest的值是一个空引用:

When you first enter the method setNotNull you get a copy of the value of nullTest in s. In this case the value of nullTest is a null reference:

------------    ------------
| nullTest |    |    s     |
------------    ------------
     |               |
    null            null

然后重新分配s:

------------    ------------
| nullTest |    |    s     |
------------    ------------
     |               |
    null         "not null!"

然后保留方法:

------------
| nullTest |
------------
     |
    null

这篇关于为什么我的Java方法不能改变传递的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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