This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Literal conversion

Charlie Swanson
Ranch Hand
Posts: 213
Could you explain the below lines of code:
1. int n2 = 4096L; // would require a specific (int) cast
2. short s1 = 32000; // ok
3. short s2 = 33000; // out of range for short primitive
In line 2, what I understand is that the number 32000 is actually assumed to be 32000 which is an integer. So infact it is:
2. short s1 = 32000 (where 32000 is an integer)

However a conversion from integer to short would that be the
the same case as line 1 which required a specific cast. In
the case from (short);
The book says since the number 32000 is the range of short,
and therefore it is accepted. Could someone please explain?
In regards to line 3 the compiler would object to line 3, due to the range of primitives. However, isn't the number 33000 an interger by default which would again need to be converted to a short since to it a narrowing type of conversion. The explaination of how it works is appreciated.

frank davis
Ranch Hand
Posts: 1479
The Rules as I understand them are this:
There is an implict narrowing for integer, char & short types only when performing a narrowing conversion if these conditions are met:
1. its an integer literal within range, or
2. its integer, char, short variable defined with final within range.

Charlie Swanson
Ranch Hand
Posts: 213
Thank you for the help.