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

i = i++

Peng Fan
Ranch Hand

Joined: May 04, 2004
Posts: 35
if i equals to 0, then assign i++ to i,but the result is still 0, however in C++, the result is 1, why here in java is 0? THX!
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9053
    
  12
The results in C++ are variable depending on the OS. The results in Java are always the same independent of the OS.

I think I would never do this in real life. You assign the value of 'i' (in this case '0') to i before the increment happens. On the other hand, if you use i = ++i, you will always increment 'i' before you assign it to 'i'.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
As Marilyn pointed out, "i = i++" is undefined in C++. This is potentially a problem since a program that returned one result when compiled in one OS may return different results when compiled in another OS. In Java, "i = i++" is defined and will always return the same result no matter which compiler or OS you use.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
The important point to remember is that in Java, the ++ operator is executed *immediately*, it's just that the result of i++ is the value of i before the increment.

That is,

i = i++;

will *first* increment i, then assign i the value of i before the increment.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Irina Goble
Ranch Hand

Joined: May 09, 2004
Posts: 91
Here is a link for C++:
C++ Style and Technique FAQ
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: i = i++