Reputation: 3
In the sample code below, why is the end value different after each method. I would expect both to display "i = 1"
public class Test {
public int i = 0;
public static void main( String args[] ) {
Test t = new Test();
t.test();
}
public void test() {
i = 0;
System.out.println( "[start a] i = " + i );
doSomethingA( i++ );
System.out.println( "[end a] i = " + i );
System.out.println( "---------------------" );
i = 0;
System.out.println( "[start b] i = " + i );
doSomethingB( i++ );
System.out.println( "[end b] i = " + i );
}
// Direct assignment of passed value
public void doSomethingA( int x ) {
i = x;
}
// Equation of passed value
public void doSomethingB( int x ) {
i += x;
}
}
The results are:
[start a] i = 0
[end a] i = 0
---------------------
[start b] i = 0
[end b] i = 1
Why does it matter what I do to 'i' in the methods, shouldn't it increment by 1 after the method ends?
In both cases I am assigning the value of 'i' to 0 inside the method.
Thanks
Upvotes: 0
Views: 105
Reputation: 124235
Add
System.out.println("i=" + i + ", x=" + x);
at start of doSomethingA
and doSomethingB
methods and you will see that in both cases
i=1, x=0
This is because in
method(i++);
first current value of i
is passed to method making x = 0
, then field i
is incremented (to 1
) and then body of method is executed. So when inside methods body you do
i = x;
you are setting i
to 0
but if you do
i += x;
you are adding 0
to current value of i
which is 1
which doesn't change value of i
.
Upvotes: 0
Reputation: 178263
Here's what happens when calling both methods from test
.
First.
i
starts out at 0
and 0
is printed. i++
is evaluated. Because it's post-increment, the expression value is the old value, 0
, so that is what's passed to doSomethingA
. The post-increment leaves i
at 1
. doSomethingA
assigns x
(0
) back to i
, so 0
is printed.
Second.
i
starts out at 0
and 0
is printed. i++
is evaluated. Because it's post-increment, the expression value is the old value, 0
, so that is what's passed to doSomethingB
. The post-increment leaves i
at 1
. doSomethingB
adds x
(0
) to i
, so i
remains 1
, and 1
is printed.
Upvotes: 1