• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question

 
Harry Kong
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whys does this print 0, not 1?
public static void main (String[] args) {
int i = 0;
i = i++; // (1)
System.out.println(i);
}
Doesn't i get incremented by 1 after assinging 0 to i on line (1)?
Here is my thinking process.
i is 0 at initialization. i gets i on line(1), which is 0, then i gets incremented by 1 with i++. Then when you print i it seems like it should print 1, not 0.
It would be perfectly understandable if i++ was getting assigned to some other variable and that variable is being printed.
It behaves like there are two different i's.
[ January 08, 2003: Message edited by: Harry Kong ]
 
Harry Kong
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just experimented a bit.
i = i++;
System.out.println(i);
behaves like
System.out.println(i++);
The second one is much more intuitive IMO.
 
Deep Chand
Ranch Hand
Posts: 133
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i++ returns the original value of i (which is 0). So, original value is again assigned to i.
if you only do i++ or do i = ++i then you will see 1 being printed.
Thanks,
Deep
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maha's technique for solving ++/-- problems:
http://www.coderanch.com/t/190825/java-programmer-SCJP/certification/Array
Be aware that i will not have the same value after
i = i++;
and after
i++;
For instance, if i = 1, after
i = i++;
i's value will still be 1.
Instead, after i++, i will be incremented to 2.
 
Harry Kong
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great technique! It helps to solve problems, but it doesn't really help me understand why that is the case To me, i = i++ doesn't make sense mathematically.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic