I was going through chapter 3 in the book OCP complete study guide, and I was wondering why short variable accepts the result of an operation on int literals, example:
short s= 1+1;
s ==> 2
while it refuses operations on int variables:
| incompatible types: possible lossy conversion from int to short
| short s=s1+s1;
I do understand why I get an error in the second operation as long as short can't accept int values without casting, but why not in the first example also. short is supposed to accept int literals only or short values.
Mustapha Elbazi wrote:but why not in the first example also. short is supposed to accept int literals only or short values.
Hanumant Deshmukh's OCAJP book page 25 goes into detail about Compile time vs run time (I couldn't think of the right keywords for CSG at the moment):
If a compiler can determine the value that a variable will take during the execution of the program, then that
variable is actually a compile-time constant. For example, if you define an int variable as
final int x = 10; then x is a compile time constant because the compiler knows tha x will
always have a value of 10 at run time. Similarly, literals such as the numbers 1, 2, and 3, or
the characters written in code within single quotes such as ’a’, or boolean values true and
false, are all compile time constants because the compiler knows that these values will never
Secondly, the "2" compile time constant is well within range for short so the compiler is happy.
The compiler is intelligent these days, so as Charles said, it can figure out that the value you are giving on the right hand side is within the range of short.
The only exception to this is when you are passing an int literal to a method which takes short as argument. In that case you have to do explicit type-cast. There is an example specifically in the JLS for this: