File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "i & i++ print same( int i) , how?" Watch "i & i++ print same( int i) , how?" New topic

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

karthik bhagnagarapu

Joined: Apr 14, 2001
Posts: 5

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

Joined: Jul 22, 2000
Posts: 9059
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.

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

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

Joined: Nov 09, 2000
Posts: 7
oops..i made a verbal mistake..
the evaluation is from left to right.
I agree. Here's the link:
subject: i & i++ print same( int i) , how?
It's not a secret anymore!