File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a simple 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 "a simple question" Watch "a simple question" New topic

a simple question

andy lau
Ranch Hand

Joined: Apr 08, 2002
Posts: 51
int i=0;

why the result is zero???
brent spearios
Ranch Hand

Joined: Apr 10, 2002
Posts: 48
The ++ is evaluated after the variable is asigned the value if you put the ++ before the variable then you would get the desired results
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
That's not exactly true.
++ is evaluated before the assignment but the value being used for the assignment is the one before the incrementation. But the bottom line is, ++ is evaluated before =.If ++ was evaluated after, we would have 1 as output.
you should maybe do a search in this forum since this topic has been discussed 1 gazillion times.
[ April 12, 2002: Message edited by: Valentin Crettaz ]

[Blog] [Blogroll] [My Reviews] My Linked In
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
Okay, short and sweet.
You have to understand the concept of a "return value" of a subexpression.
Given i++, the return value of this would be the original value of i prior to incrementation; on the other hand, for ++i the return value would be the incremented value of i.
The = operator has the lowest priority, so everything on the RHS (right hand side) would have to be resolved first, and the value on the LHS (left hand side) would have to be the return value of the RHS.
In the example above, the RHS went first so i was really incremented to 1, but the return value is 0. The LHS therefore receives the value of 0, overwriting whatever previous value was there.
The same argument goes whenever you pass a subexpression to a method as a parameter. The value of the parameter is whatever the return value of the subexpression.
For example, given

The value of i here is 1, but println() prints out the return value of i++, which is 0.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Two Examples:
int i = 0;
System.out.println(i++); //prints 0
int i = 0;
System.out.println(++i); //prints 1
It depends on the position of the incrementor, ++. This also aplies to "--".
hope it helps
Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
class Test7
public static void main(String args[])
int var = 20, i=0;
if( i++ > var) break;

This code prints 19 and not 20.

I agree. Here's the link:
subject: a simple question
It's not a secret anymore!