Reputation: 738
The output of this code is:
c: 1 , id: 0
I want to know why the output is not:
c: 0 , id: 1
class A {
private static long c;
private final long id = c++;
public A() {
print("c: " + c + " , id: " + id);
}
}
Upvotes: 1
Views: 246
Reputation: 897
because you use c++.
c++ means you first save the variable to your id and then increment ++.
If you'd use ++c you would first increment and then save it to id.
But it will return c:1 id:1 because c++ means c = c+1!
If you say: id = c+1 you will get c:0 and id:1
Upvotes: 1
Reputation: 1504004
Because an expression like c++
operates like this:
c
; remember this (e.g. tmp = c
;)c
tmp
)So in this case, you start off with c = 0
, so id
becomes 0... but c
is incremented in the process, so c
is 1 after the expression has been evaluated.
See section 15.14.2 of the Java Language Specification for more details. Extract:
At run-time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.
Upvotes: 4
Reputation: 59633
id = c++
assigns the value of c
to id
, then it increments c
. It is as if you did the following:
c = 0;
id = c; // assigns zero
c = c + 1;
Try id = ++c
instead.
Upvotes: 1