• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Literal conversion

 
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 1479
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for the help.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic