1

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
sunleo
  • 10,589
  • 35
  • 116
  • 196

3 Answers3

3

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)

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
3

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
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

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)

Jeremy Unruh
  • 649
  • 5
  • 10