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?

alf
  • 8,377
  • 24
  • 45

4 Answers4

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.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
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

wrschneider
  • 17,913
  • 16
  • 96
  • 176
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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
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.

darijan
  • 9,725
  • 25
  • 38