变量无法更改 [英] variable can not be changed

查看:136
本文介绍了变量无法更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么变量s不会被2改变

Why the variable s is not changed by 2

public class Test {
  static void getVal(int s) {
    s= 2;
  }

  public static void main(String arg[]) {
    int s = 0;
    getVal(s);
    System.out.println(s);
  }
}


推荐答案

As Felix在评论中说,在Java中,参数是按值传递的。

As Felix says in the comment, in Java arguments are passed by value.

如果我们使用不同的变量名,它会更清楚:

It's clearer if we use different variable names:

public static void main(String arg[]) {
  int x = 0;
  method(x);
  System.out.println(x); // Prints 0
}

static void method(int y) {
  y = 2;
}

当你打电话给方法(x),评估 x 的值,该值成为 y 的初始值。这是两个变量之间的唯一连接。更改 y 的值不会更改 x 的值。

When you call method(x), the value of x is evaluated, and that value becomes the initial value of y. That's the only connection between the two variables. Changing the value of y doesn't change the value of x.

现在有了引用类型变量,它可能出现,好像情况并非如此:

Now with reference type variables it may appear as if that's not the case:

public static void main(String arg[]) {
  StringBuilder x = new StringBuilder();
  method(x);
  System.out.println(x); // Prints "appended"
}

static void method(StringBuilder y) {
  y.append("appended");
}

看起来有点像你改变了 x 的值 - 但你真的没有。 x y 的值只是对象的引用 ...两者 x y 引用同一个对象,追加 call已更改对象内的数据。我喜欢在这里使用的类比是房子:作为调用者的方法,我可以给你一张纸,上面写着我的地址。该地址相当于引用,而我的房子是对象

It looks a bit like you've changed the value of x - but you really haven't. The values of x and y are just references to an object... both x and y refer to the same object, and the append call has changed the data within the object. The analogy I like to use here is with houses: as the method caller, I can give you a piece of paper with my address written on it. That address is the equivalent of the reference, whereas my house is the object.

你可以改变两件事:


  • 您可以将前门涂成红色,这样就可以对物体进行更改。我下次看房子时会看到这种变化。

  • 你可以改变写在你纸上的地址。

这些都没有改变我居住的地方 - 无论你做了什么,我对我的房子的引用副本都和以前一样。

Neither of these makes a change to "where I live" - my copy of the reference to "my house" is the same as it was before, whatever you've done.

当涉及到类的行为时,会产生一个常见的神话,即Java通过引用按值传递原语 - 这简直是不真实的。 Java按值传递所有参数 - 但您需要了解表达式的值始终是原始值还是引用,而不是对象。

The behaviour when it comes to classes leads to a commonly-stated myth that "Java passes primitives by value and objects by reference" - that's simply untrue. Java passes all arguments by value - but you need to understand that the value of expression is always either a primitive value or a reference, never an object.

这篇关于变量无法更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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