• 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

int or short

 
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Am I correct by saying 22 is explicitly an int?
as 22.2 is explicitly an double.

Then why does

short s = 22;

work with out a cast
shouldn't it have to be

short s = (int)22;

as

Short sObject = new Short(22);
won't work as it knows 22 is an int
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java will automatically do a narrowing cast on constant int expressions that can be evaluated at compile time when they are assigned to byte, short, or char, provided that they will fit.
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,


Short sObject = new Short(22);
won't work as it knows 22 is an int



Because implicit narrowing is done automatically for assignments, but not automatically done while evaluating method parameters..

So you to do explicit cast to pass a Integer literal to a method that accepts short value.

Look at jls for more information.

Thanks,
Raja
 
Kris Reid
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If that is true why doesn't implicit narrowing work for a float.
i.e. float f = 5.5
needs a cast
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Kris Reid:
...why doesn't implicit narrowing work for a float?


With floating-point numbers, it's not just about range. "Precision" also becomes an issue due to the way in which these values are stored.

See this thread:
https://coderanch.com/t/247234/java-programmer-SCJP/certification/method-parameter
[ January 06, 2005: Message edited by: marc weber ]
 
Of course, I found a very beautiful couch. Definitely. And this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic