Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why mixing + and cast does not produce an error in "+(int)+(long)-1"?

Tags:

java

Why does this print 1?

import java.util.*; import java.lang.*; import java.io.*;   class Main {     public static void main (String[] args) throws java.lang.Exception     {         // your code goes here         System.out.println((byte)+(short)-(int)+(long)-1);     } } 

Can we mix casting and +,- unary operators? I know that we can do casting multiple times, but why doesn't putting + ,- unary operators in between produce an error?

like image 412
prab2112 Avatar asked Feb 18 '15 11:02

prab2112


1 Answers

You are not adding nor substracting. Those + and - operators are unary sign operators.

See documentation at The Unary Operators section.

The sequence at stake:

(byte)+(short)-(int)+(long)-1 

is evaluated from right to left like this:

the initial value is -1
casting to long (which is still -1)
unary + sign (still -1)
casting to int (still -1)
unary - sign (now the value is 1)
so on (the value remains 1 until the end)

like image 103
Paco Abato Avatar answered Sep 21 '22 13:09

Paco Abato