I've come across this particularly evil example of code:
So what will happen here? We all know that an int can't be assigned to a byte without an explicit cast, so obviously the code won't compile. However, to my surprise it does! However, if you take out the final modifier for the i variable, the code won't compile. Moreover, if i gets assigned 200 (something larger than the range of a byte) and is final then it won't compile.
I'm just wondering what is happening behind the scenes. Is the compiler reclassifying i as a byte variable since it knows the value at compile time and knows that it can't change during runtime with the final modifier?
The compiler will automatically narrow down the assignment. Dan Chisholm on his website explains this very well. Visit his site and your doubt's about automatic conversions will be DONE forever.
The rule is that in an assignment statement if the right hand side of the assignment is a COMPILE TIME CONSTANT of type byte,char,shot or int then it will be automatically converted(narrowed) to the reference type of the left hand side.
r final variables the only COMPILER TIME CONSTANT.. ??
Only those who will risk going too far, Can possibly find out how far one can go! <br />happiness is journey and not destination<br /> <br />A Nayak<br />----------------------------------<br />SCJP 1.4<br />SCWCD 1.3<br />SCBCD 1.3
As a corollary to the above post, this won't compile either. Although it's a bit off-topic, I notice it in a few mock exams.
SCJP 1.4<br />(WIP) SCJD B&S v2.3.3
Joined: May 11, 2004
could you tell me why there will be no implicit narrowing cast to int in your example.
Please explain this concept.
Joined: Jul 31, 2004
The rules for variable assignments do not apply to arguments passed to methods. I can remember that Dan's mock has an explanation about this... it seem the developers of Java chose not to perform an implicit cast in values passed as arguments because it would be dificult to determine which method should be called in case of overloading. Imagine this scenario:
As you can see, problems may arise here if the implicit casting is performed in arguments to methos. The value of x fits in an int, but its type is a long.... what should the compiler do to determine the method the programmer wants to be called?
Stefan. [ August 20, 2004: Message edited by: Stefan Guilhen ]