Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

postfix ++ operator (exam question for SCJP)

Status
Not open for further replies.

engdict

Programmer
Jan 8, 2003
10
US
The following code outputs 2, not 3. Any insight as to why would be very useful. (The corresponding code in C++ outputs 3)

int i = 2;
i = i++;
System.out.println(i);

TIA.
 
java does not handle prefix and postfix the same way that other lang's do. in java, prefix will change the value of the variable but postfix will not.

int i = 2;
i = i++;
System.out.println("i: " + i);

will give the output of 3.

hope this helps.
 
both prefix and postfix will increase the variable by one.
however, whether the "++" is near of far from the "=" acts differently.

j=i++ meane j=i
j=++i means j=(i+1)

in other words, if "++" is near "=", then it counts. otherwise, it does not affect the initialization value of "j".
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top