java基础复习三:i++与++i以及表达式

来源:互联网 发布:hadoop tensorflow 编辑:程序博客网 时间:2024/06/05 19:05

虽然知道++i一个是先计算在赋值,i++是先赋值再计算,但是有时候还是会搞不清楚,复习一下。

不涉及表达式时

测试代码:

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

输出结果:

i=2k=1

这个结果理解起来没问题。

但是如果有表达式呢?

包含其它表达式的时候

赋值给第三方变量
测试代码:

public static void main (String[] args) {        int i = 1;        int k = i++;        System.out.println("i=" + i);        System.out.println("k=" + k);    }

输出结果:

i=2k=1

从结果上看,k的值是i未加1之前的值,i的值是加1之后的值,也就是i++是先赋值,再计算。

测试代码:

public static void main (String[] args) {        int i = 1;        int k = ++i;        System.out.println("i=" + i);        System.out.println("k=" + k);    }

输出结果:

i=2k=2

从结果上看,k的值是i加1之后的值,i的值是加1之后的值,也就是i++是先计算,再赋值。

这种情况理解起来也没有问题。

赋值给自身
测试代码:

public static void main (String[] args) {        int i = 1;        i = i++;        System.out.println("i=" + i);        //System.out.println("k=" + k);    }

输出结果:

i=1

我以为会输出2,可是事实确实1,我一时想不明白就去oracle官网找i++和i–的语言特性说明。
看到了下面这个说明:

The type of the postfix increment expression is the type of the variable. The resultof the postfix increment expression is not a variable, but a value.At run time, if evaluation of the operand expression completes abruptly, thenthe postfix increment expression completes abruptly for the same reason and noincrementation occurs. Otherwise, the value 1 is added to the value of the variableand the sum is stored back into the variable. Before the addition, binary numericpromotion (§5.6.2) is performed on the value 1 and the value of the variable. Ifnecessary, 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 isstored. The value of the postfix increment expression is the value of the variablebefore the new value is stored

我英语比较垃圾,配合百度翻译,勉强理解了一下,大概意思是:

后缀计算i++和i–,计算表达式计算未结束之前i的值是原来的值,表达式确定结束了,会把原值加一之后的值赋值给i,特别注意i++和i–的执行结果是值不是变量(the postfix increment expression is not a variable, but a value)

现在再看一下这个表达式:i = i++;
等号的意思我们都知道,左边的计算结果等于右边的计算结果,右边的计算结果:
i++计算结果是1;也就是说
i = i++等效于 i = 1;,所以输出结果是1。

同样的道理 ++i、–i、i–计算结果都是值,然后把值赋给变量。

比较大小的时候

上面我知道了,在用++ 、–的时候都是用的计算后的值,所以上面的情况我都理解了,但是比较大小的时候呢?

测试代码:

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

输出结果:

true

结果是true,可以得知,k也是和i++的值进行比较的,也就是 k==1,所以在比较中++、–也是用的计算后的值。

总结

1、i++和i–返回的值是原来i的值,但是i的值都会加一或减一;
2、++i和–i返回的值是加一或者减一后的值,i的值也会加一或减一;
3、++和–用在复杂表达式中时候,使用的都是++和–表达式计算后的值;