byte b = 100 ;
compiles without any errors, but
int i = 100 ;
byte b = i ;
throws an error. Why? Even when assigning 100 directly to b, we are assigning an int literal. So why did I get an error?
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.
Here
100is a compile time constant. And hence can be assigned to thebyte.Now in this case, since
iis not declaredfinal, so it is no more acompile timeconstant. And in that case, you can later on come and modify the value ofi, in between theinitialization of i, andassignment of i to byte, as in the above case. Which will certainly fail.That is why compiler does not allow the assignment of
itobytetype.But, you can use an explicit casting for it to compile, which may of course
crashat runtime. By doing an explicit cast, you tell the compiler that – “I know what I’m doing, just do it for me”. So, it will not bother about runtime behaviour of that casting, and will trust you that you are not doing anything wrong.So, either you can declare your
int iasfinal, or you need to do the casting: –So, when you use a value
130and cast it tobyte, you pass through thecompiler, but will certainly crash at runtime. And this is the problem that thecompilerwas trying to avoid.Now let’s go back the first case: –
The above assignment will now fail to compile. Because even though the value
128is a compile time constant, it is not big enough to fit in abyte, and that thecompilerknows.