-2

I do not understand why 103 and 109 are printed.
If the increment operator is being used, should it not be 104 and 109?

int h = 103;
int p =5;
System.out.println(h++);
System.out.println (h+p);`

Actual output:

103
109

Expected output:

104
105
Dushyant Tankariya
  • 1,432
  • 3
  • 11
  • 17
  • 1
    Welcome to stack overflow, Please go through the [tour](https://stackoverflow.com/tour), the help center and the [How to Ask](https://stackoverflow.com/questions/how-to-ask) sections to see how this site works and to help you improve your current and future questions, which can help you get better answers. Please also have a look at [How do I ask](http://meta.stackexchange.com/a/10812/162852) – Dushyant Tankariya Oct 04 '19 at 13:37
  • 1
    Possible duplicate of [what is the difference between i++ & ++i in for loop (Java)?](https://stackoverflow.com/questions/2315705/what-is-the-difference-between-i-i-in-for-loop-java) – AElMehdi Oct 04 '19 at 13:40
  • 2
    Why would `h+p` ever be 105? – f1sh Oct 04 '19 at 13:45
  • 1
    Possible duplicate of [Is there a difference between x++ and ++x in java?](https://stackoverflow.com/questions/1094872/is-there-a-difference-between-x-and-x-in-java) – Villat Oct 04 '19 at 13:51
  • The increment occurs after the print, and as for the second expected out put, I have no idea why you would this it would be 105 – johnny 5 Oct 04 '19 at 13:55

1 Answers1

4

You are confusing h++ and ++h: one increments and then returns the old value, the other increments and then returns the new value.

So, the first print still outputs the old value (ie 103) because you're using the post-increment operator, but h still does increase by one, therefore: h+p = 104+5 = 109

Azrael
  • 175
  • 1
  • 12