1
public class F { int test(int e) { System.out.println("ok"); return e; } public static void main(String[] args) { int y = 8; F f = new F(); int i = f.test(y++); System.out.println(i); } } 

the output of this program is 8, which is what I expect.

public class Sa { public static void main(String[] args) { int i = 8; i++; System.out.println(i); } } 

For this program, the output is 9, which is surprising: why we are getting different values using the same values and the same increment operator in both programs?

2
  • Please format your question. Commented Jun 10, 2013 at 15:28
  • You can do the following: 1) try to use a breakpoint to debug; 2) google; 3) make your question better looking. The current post shows virtually none effort. Commented Jun 10, 2013 at 15:29

4 Answers 4

5

y++ post-increments. That means it increments after the expression is evaluated.

When you run

i=f.test(y++) 

then the value passed into the test method is the one before the increment took place.

In your other code sample i++ is evaluated by itself so the increment takes place before the println.

Change the code in your first sample to ++y and you should get 9.

Sign up to request clarification or add additional context in comments.

Comments

1

i++ is a postincrement operator, which means that it evaluates to the current value of i and then increments after use.

I would expect

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

would print 8 then 9.

You might have meant ++i which is preincrement

Comments

0

y++ is post-increment.

It pass the value and then increments.So you are getting the previous value before incrementing.

In second case you are printing the incremented value.

Comments

0

y++ in the

i=f.test(y++) 

is evaluated after the test() method is run. So, the test gets the value 8 and prints 8.

Incrementing it in the Sa class is equal to:

i++; // is equal to i+=1 OR i = i + 1; 

But, that is not why we use the incrementation (++). The purpose of it is the side-effect that it has in an expression.

Exactly in your example, you want to pass in the 8, but increment it to 9 after the test has been executed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.