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

java

Solution

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

`+ - + -` are assigning the sign (Unary Operators) to the number, so `-` then `+` then `-` and finally `+` gives you `1`.

If we just ignore the type casts 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

Problem

I stumbled upon this code on internet ``` public class Test { /** * @param args */ public static void main(String[] args) { int i = (byte) + (char) - (int) + (long) - 1; System.out.println(i); } } ``` It prints `1`. Can i know why ? Here is the source --> http://www.javacodegeeks.com/2011/10/weird-funny-java.html

Original source

Related problems