java - 作业给出了意想不到的答案

标签 java

今天我遇到了以下问题,我似乎找不到解决方案:

int i, j, k;

i = j = k = 3;

i = k++;

所以对我来说,变量“i”现在必须具有值 4 似乎是合乎逻辑的,因为我们将“k”的增量分配给它。在多项选择测试中,第三行之后的正确值改为:

k = 4

i != 4

既然我们将 k 的增量分配给了 i,为什么给定的解决方案与我的预期完全相反? 提前致谢!

最佳答案

首先,正如 JB Nizet 所指出的,不要这样做。偶尔我会在另一个表达式中使用后缀增量,例如 array[index++] = value; 但为了清楚起见,我经常将它分成两个语句。


我不打算回答这个问题,但是所有答案(在发布时)都犯了同样的错误:这不是时间问题 完全没有;这是表达式 k++ 的值的问题。

i 的赋值发生在 k 的增量之后 - 但是表达式 k++ 的值是k 的原始值,而不是增量值。

所以这段代码:

i = k++;

相当于:

int tmp = k;
k++;
i = tmp;

来自 section 15.14.2 of the JLS (强调我的):

[...] Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

这种差异非常重要,如果您不使用后缀表达式进行赋值,而是调用方法,则很容易看出这一点:

public class Test {

    private static int k = 0;

    public static void main(String[] args) throws Exception {
        foo(k++);
    }

    private static void foo(int x) {
        System.out.println("Value of parameter: " + x);
        System.out.println("Value of k: " + k);
    }
}

结果是:

Value of parameter: 0
Value of k: 1

如您所见,k 在我们调用该方法时已经递增,但是传递给该方法的值仍然是原始值。 p>

关于java - 作业给出了意想不到的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21510573/

相关文章:

java - "update classpath"在Java或SpringBoot中是什么意思?

java - 从 App Engine 构建缓存时如何平衡负载?

java - 无法将 BasicDBList 转换为数组 (java)

java - Collections.sort 与 Arrays.sort - Java 中

java - hibernate 查询: new DTO clause not working

java - 如何在不嵌套的情况下在 lambda 中链接 Optional#ifPresent()?

java - 我如何将一个字符串数组从servlet发送到jsp并在jsp中接收它

java - 循环内的计时器?

java - 如何正确检查2个Calendar对象表示的日期(年月日)是否相同?

java - 如何找出给定的字符串已经在 J​​ava 字符串池中?