What is the Difference between postfix and unary and additive in java [duplicate]

强颜欢笑 提交于 2019-12-11 12:35:21

问题


Please help me to understand what is the difference between two "TRUE" and "FALSE" outputs. and also guide me how to get this logic and operator related topics in Oracle Docs.

int i = 1;
int j = 2;

System.out.println(i==j--);// FALSE
j = 2;
System.out.println(i==j-1);//TRUE
j = 2;
System.out.println(i==--j);//TRUE

回答1:


i == j-- means i == j; j = j - 1;

i == j-1 means i == (j-1);

i == --j means j = j - 1; i == j;

Here is the operator precedence table, in order from highest to lowest. For example, - has higher precedence than ==, which is why i==j-1 means i==(j-1)




回答2:


The equivalences are in the following table, as are the explanations where i is 1 and j is 2 at the start of each line:

i==j--;   i==j; j--;  // 1==2 is false, j <- 1
i==j-1;   i==j-1;     // 1==(2-1) is true, j does not change
i==--j;   --j; i==j;  // j <- 1, 1==1 is true



回答3:


The difference is:

j-- happens after the call (so during the comparing it evaluating i==j is j's current value. The -- occurs after (postfix)

j-1 is part of the expression so happens as part of the computation

--j is pre function call so it's subtracted before (prefix)



来源:https://stackoverflow.com/questions/16182477/what-is-the-difference-between-postfix-and-unary-and-additive-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!