• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Literal conversion

 
Charlie Swanson
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for the help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic