Question

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 =+?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top