Denis Tulskiy
Denis Tulskiy

Reputation: 19177

Weird java behavior with casts to primitive types

This was probably asked somewhere but I couldn't find it. Could someone clarify why this code compiles and prints out 1?

long i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);

Upvotes: 30

Views: 2421

Answers (3)

david van brink
david van brink

Reputation: 3642

Unary operators and casting :)

+1 is legal

(byte) + 1 is casting +1 to a byte.

Sneaky! Made me think.

Upvotes: 5

Dave Newton
Dave Newton

Reputation: 160191

Because both '+' and '-' are unary operators, and the casts are working on the operands of those unaries. The rest is math.

Upvotes: 5

Mysticial
Mysticial

Reputation: 471249

It's being parsed as this:

long i = (byte)( +(char)( -(int)( +(long)(-1) ) ) );

where all the + and - operators are unary + or -.

In which case, the 1 gets negated twice, so it prints out as a 1.

Upvotes: 42

Related Questions