Reputation: 2089
Given the following code snippet:
int i = 0;
int y = + ++i;
System.out.println(y);
The result is 1. Why is this a valid declaration? Can anyone explain what is =+?
Upvotes: 1
Views: 76
Reputation: 3941
The first plus after the equals sign is the sign of the value. So it means it is a positive number.
int y = - ++i;
would return -1
Upvotes: 2
Reputation: 12754
Here +
indicates the value is positive or not,i.e. unary
operator and if you changes the value to -
then the answer will be -1
. i.e. int y = - ++i;
will give -1
.
Upvotes: 2
Reputation: 122008
Java guarantees that it will be evaluated left-to-right
. Specifically, ++ has higher precedence
than +. So it first binds those, then it associates the addition operations left to right
Upvotes: 0
Reputation: 206896
int y = + ++i;
The first +
in this line is simply the unary +
operator (see: Assignment, Arithmetic, and Unary Operators). It does nothing. It's similar to the unary -
operator. The line above is equivalent to:
int y = ++i;
which increments i
and then assigns the new value of i
to y
.
Upvotes: 7