aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes int or short Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "int or short" Watch "int or short" New topic
Author

int or short

Kris Reid
Ranch Hand

Joined: Jan 05, 2005
Posts: 247
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

Joined: Mar 13, 2004
Posts: 1272
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.


Mike Gershman
SCJP 1.4, SCWCD in process
Rajasekar Elango
Ranch Hand

Joined: Sep 13, 2004
Posts: 105
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


SCJP 1.4
Kris Reid
Ranch Hand

Joined: Jan 05, 2005
Posts: 247
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

Joined: Aug 31, 2004
Posts: 11343

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 ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
wood burning stoves
 
subject: int or short