为什么我不能在void方法中增加整数 [英] Why I cannot increment integer in void method

查看:120
本文介绍了为什么我不能在void方法中增加整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑为什么在这个小例子中仍然是0:

I am really confuse why in this small example i is still 0:

public static void main(String[] args) {
    int i = 0;
    inc(i);
    System.out.println(i);
}

private static void inc(int i) {
    i++;
}

可能非常简单,但我看不到它

probably very easy question but I dont see it

推荐答案

Java按值传递参数。

Java passes parameters by value.

所以 i inc 实际上只是原始的副本 i 方法中。您递增该副本,但这对原始变量 i 外部没有影响。

So the i in the method inc is really just a copy of the "original" i in the main method. You increment that copy, but that has no influence on the original variable i outside.

有关更详细的说明,请参见此问题

See this question for a more detailed explanation.

这篇关于为什么我不能在void方法中增加整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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