Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
karthik bhagnagarapu
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9080
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Magesh Lakshmi
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oops..i made a verbal mistake..
the evaluation is from left to right.
 
I've never won anything before. Not even a tiny ad:
Thoughts on deprecation in Java
https://coderanch.com/t/683016/java/Deprecation-Java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!