GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes i & i++ print same( int i) , how? 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++ print same( int i) , how?" Watch "i & i++ print same( int i) , how?" New topic
Author

i & i++ print same( int i) , how?

karthik bhagnagarapu
Greenhorn

Joined: Apr 14, 2001
Posts: 5
hi,

public class Test{
private int i;
Test(int ii){
i = ii;
}
public static void main(String[] args){
Test t = new Test(5);
1) System.out.println(t.i); // this prints 5
2) System.out.println(t.i++);// so does this, a 5.
}
}
now for 1) and 2) didn't i invoke methods on the object System.out? my guess the interpreter ignores the ++ sign,
but why? i hope someone can help me. thx in advance.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9046
    
  10
Originally posted by Gareth Leachman:
because it is postfix, the operating system will use t.i with its value of 5, and then increment i by 1. This is the nature of postfix operators.

which is why I recommend that you avoid writing your code this way. It can be confusing. Put the increment on a separate line.

JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Magesh Lakshmi
Greenhorn

Joined: Nov 09, 2000
Posts: 7
Try printing out the value of t.i after the statement
System.out.println( t.i++);
Then u will notice the value of t.i is incremented.
This is b'cos the evaluation in this case is from right to left, the variable is just printed first and incremented.
Magesh Lakshmi
Greenhorn

Joined: Nov 09, 2000
Posts: 7
oops..i made a verbal mistake..
the evaluation is from left to right.
 
GeeCON Prague 2014
 
subject: i & i++ print same( int i) , how?