It works as it is evaluated at compile time by the compiler only when .java is converted to .class file. And compiler treats 7 as constant and checks it value range, if it is assignable to short then it assigns 7 to it.
when you write:
then assigning 7 to short s is delayed to runtime and performed by JVM, and JVM treats 7 as int type,
It will complain you saying "cannot assign int to short".
so it asks for explicit casting.
Punit Singh wrote:then assigning to 7 to short s is delayed to runtime and performed by JVM,
I feel this sentence could be better phrased, just feel this is telling the right thing in a wrong way.
Maybe, it can be elaborated a bit more to be accurate........ my feelings though....
After all, we get a compile error.
Maybe what you say is right, but I see no reason why method(7) couldn't be made to work. It's true that the invocation is made at runtime, but the compiler could analyze the method signature, see that 7 is a compile time constant in range of short, and insert a cast at compile time. It's just that that's not the way things work. Maybe I'm missing some other reason why it's not allowed.
All code in my posts, unless a source is explicitly mentioned, is my own.
Your mother was a hamster and your father was a tiny ad: