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
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
Because after operator precedence rules are applied it becomes equivalent to:
int i = (byte) ((char) -((int) ((long) -1)));
which evaluates to -(-1)
which is 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With