2
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

2
  • Those are Post and pre incrementation Commented Jan 7, 2022 at 17:54
  • in i++ == i, i as 10 will be used from i++, which will be increment to 11, then it'll be compared to latter i which value is now 11. i.e, 10 == 11. Commented Jan 7, 2022 at 18:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This clears everything.Thank you
@new1one can you mark as right answer then?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.