Possible Duplicate:
Weird java behavior with casts to primitive types
Why does this code in Java,
int i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);
prints 1? Why does it even compile?
Source: Java Code Geeks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
What you are doing is combining type casts with unary operators.
So let’s see:
First, you have the value
-1, which you cast to the typelong.Then, you perform the unary operation
+, which doesn’t change the value, so you still have(long) -1.Then, you cast it to int, so we now have
int -1. Then, you use unary operator-, so we have-(-1), which is1.Then you cast it to char, so we have
char 1. Then, you use unary operator+, so you still have1.Finally, the value is cast to
byte, so you havebyte 1. And then it is once again (implicitly) cast toint.