问题
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