# unable to understand the output

nishant vats

Greenhorn

Posts: 23

Andris Jekabsons

Ranch Hand

Posts: 82

posted 11 years ago

In the first example "a[ ++n ]" the increment is performed BEFORE evaluating the value of n.

So, the expressions becomes "a[ 0+1 ] = ++n", that is: "a[ 1 ] = ++n".

n now has value of 1, and it is incremented on the left side of " = ":

"a[ 1 ] = 1+1", that is: "a[ 1 ] = 2"

a[ 0 ] remains with the default value of 0.

In the second example "a[ ++n ]" the increment is performed AFTER evaluating the value of n.

So, the expressions becomes "a[ 0 ] = ++n".

Only then n is assigned the value of 1, and it is incremented on the left side of " = ":

"a[ 0 ] = 1+1", that is: "a[ 0 ] = 2"

a[ 1 ] remains with the default value of 0.

So, the expressions becomes "a[ 0+1 ] = ++n", that is: "a[ 1 ] = ++n".

n now has value of 1, and it is incremented on the left side of " = ":

"a[ 1 ] = 1+1", that is: "a[ 1 ] = 2"

a[ 0 ] remains with the default value of 0.

In the second example "a[ ++n ]" the increment is performed AFTER evaluating the value of n.

So, the expressions becomes "a[ 0 ] = ++n".

Only then n is assigned the value of 1, and it is incremented on the left side of " = ":

"a[ 0 ] = 1+1", that is: "a[ 0 ] = 2"

a[ 1 ] remains with the default value of 0.

nishant vats

Greenhorn

Posts: 23

Joe Sondow

Ranch Hand

Posts: 195

posted 11 years ago

nish vats, that seems like a reasonable assumption but it turns out to be incorrect. The left-hand operand is evaluated first in order to determine the variable that will receive the newly assigned value. The entire procedure is described in the JLS 15.26.1.

SCJA 1.0 (98%), SCJP 1.4 (98%)

Consider Paul's rocket mass heater. |