File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int or short

 
Kris Reid
Ranch Hand
Posts: 247
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Mike Gershman
Ranch Hand
Posts: 1272
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
Rajasekar Elango
Ranch Hand
Posts: 105
  • 0
  • Mark post as helpful
  • send pies
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • 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:
http://www.coderanch.com/t/247234/java-programmer-SCJP/certification/method-parameter
[ January 06, 2005: Message edited by: marc weber ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic