Reputation: 301
I was asked to explain why the following snippet prints 1. I have stared at it for a while but not yet able to say why it prints out 1 or even why it does compile. Can someone kindly tell me why?
int i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);
Upvotes: 1
Views: 243
Reputation: 45339
This is just a sequence of casts and number/char conversions:
int i = (byte) +(char) -(int) +(long) -1;
can be made verbose as:
int a = -1;
long b = (long) a;
int c = (int) -b; //makes it positive
char d = (char) c;
byte e = (byte) d;
int f = e;
System.out.println(f);
Upvotes: 2
Reputation: 394026
You have here 4 casting operators and 4 +/- operators.
Since +/- can't be applied to casting operators, the only way to evaluate this expression is by treat the -
and +
as unary operators :
int i = (byte) (+ ((char) (- ((int) (+ ((long) (- 1)))))));
-1 int
-1 long
-1 long
-1 int
--1 == +1 int
1 char
1 char
1 byte
1 int
Upvotes: 1