Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird java behavior with casts to primitive types

Tags:

java

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); 
like image 862
Denis Tulskiy Avatar asked Oct 28 '11 03:10

Denis Tulskiy


1 Answers

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.

like image 71
Mysticial Avatar answered Oct 04 '22 01:10

Mysticial