Skip to content
Advertisement

Confusion with increment operators in Java in conditional statements

int i = 10;
if(i++ == i)
System.out.println(i + " is good");
else
System.out.println(i + " is bad");

int j = 20;
if(++j == j)
System.out.println(j + " is good");
else
System.out.println(j + " is bad");

So when thinking about the output my thought process went like this :

for the first if condition I thought that since its post increment operator , i value will be used first and then increased so it will execute the if condition and increment the value of i therefore printing output 11 is good

for the second if condition I thought that since tis pre increment operator, i value will be increased first and then used so the else condition will execute and hence print 21 is bad.

But when checking it comes as 11 is bad and 21 is good

Where am I thinking wrong

Advertisement

Answer

In the first case you’re comparing 10 (not yet incremented) to 11 (already post-incremented when evaluating first i++)

In the second case you’re comparing 21 (pre incremented) to 21 (post-incremented by earlier evaluation)

Your thinking was good, however you’re not factoring what happens with second i/j in the equals condition

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement