Peter Jaloveczki
Peter Jaloveczki

Reputation: 2089

Java primitive declaratiron

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

Answers (4)

das Keks
das Keks

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

Shreyos Adikari
Shreyos Adikari

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

Suresh Atta
Suresh Atta

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

Jesper
Jesper

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

Related Questions