Why is "int i = (byte) + (char) - (int) + (long) - 1" equal to 1?

I came across this code online

public class Test { /** * @param args */ public static void main(String[] args) { int i = (byte) + (char) - (int) + (long) - 1; System.out.println(i); } } 

He is typing 1 .

May I find out why?

Here is the source β†’ http://www.javacodegeeks.com/2011/10/weird-funny-java.html

+7
java
source share
3 answers
 int i = (byte) + (char) - (int) + (long) - 1; ^-------^--------^-------^ Type casting 

+ - + - assigned the sign ( Unary Operators ), so - then + then - and finally + gives you 1 .

If we just ignore the cast type, we have (+(-(+(-(1)))))=1

Equivalent code:

 long a = (long) - 1; int b = (int) + a; char c = (char) - b; int finalAns = (byte) + c; System.out.println(finalAns); // gives 1 
+15
source share

Since after applying the rules of operator precedence, it becomes equivalent:

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

which calculates -(-1) , which is 1 .

+14
source share

Due to type casting, this is equivalent

 public class Test { /** * @param args */ public static void main(String[] args) { long a1 = -1; int a2 = a1; //still -1 char a3 = -a2; // 1 byte a4 = a3; // 1 int i = a4; // 1 System.out.println(i); } } 
+6
source share

All Articles