File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question" Watch "Question" New topic
Author

Question

Harry Kong
Ranch Hand

Joined: Dec 06, 2002
Posts: 41
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 ]

SCJP 1.4
Harry Kong
Ranch Hand

Joined: Dec 06, 2002
Posts: 41
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

Joined: Dec 17, 2002
Posts: 133
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

Joined: Aug 26, 2001
Posts: 7610
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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Harry Kong
Ranch Hand

Joined: Dec 06, 2002
Posts: 41
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
 
subject: Question