【发布时间】:2019-03-30 20:58:49
【问题描述】:
我有一个关于 Java 是按值传递的问题。我知道在方法之外声明的变量不会改变它们的值,因为当我对变量调用 I 方法时,该方法只会使用分配给它们的值。但是在这种情况下,我不明白为什么 int result 没有得到 2 的值。由于 increment() 会得到 x 的值,所以 1 并将其递增 1 并将值存储在 result 变量中。
public class Increment {
public static void main(String[] args) {
int x = 1;
System.out.println("Before the call, x is " + x);
int result = increment(x);
System.out.println("After the call, x is " + result);
}
public static int increment(int n) {
return n++;
}
}
【问题讨论】:
-
尝试返回 ++n;而是
-
根据@eran 的评论,要获得您需要的内容,您需要使用
++n。
标签: java methods pass-by-value