gpt4 book ai didi

Java - 按值传递示例

转载 作者:行者123 更新时间:2023-12-02 10:39:49 25 4
gpt4 key购买 nike

我有一个关于 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++n 的值增加1,但返回之前的值。因此 increment(x) 返回 x,而不是 x+1

关于Java - 按值传递示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53002965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com