Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Increment operation question

 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading over some posts in the SCJP forum and there was a question about the increment operation. Alhough I think I understood the answer there, I came up with a puzzling problem of my own that I cannot figure out.

Consider this code:


the output is:

1
0

Although I can't follow the flow to figure out why.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i = j++; //i is set to 0, after which j is incremented to 1
j = i++; //j is set to 0, after which i is incremented to 1
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then why is the output of System.out.println(i) 1 ? Sorry, I'm slow
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
nevermind, I see, i is incremented in the second assignment. j = i++; Told you I was slow.
 
Shaan Shar
Ranch Hand
Posts: 1249
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well this is such a simple solution that Java works on Stack Memory for local Variables thus the value of J is still 0. I hope you can understand now.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic