aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes doubt on casting 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 "doubt on casting" Watch "doubt on casting" New topic
Author

doubt on casting

MInu
Ranch Hand

Joined: Oct 09, 2003
Posts: 517
float is 32 bit in size and long 64 still then it is possible to do as follows

float a = 10.003f;
long l = 922l;
a=l;

so is it not broadning.
can you please explain.
[ January 19, 2005: Message edited by: minu su ]

God Gave Me Nothing I Wanted<br />He Gave Me Everything I Needed<br /> - Swami Vivekananda
Stevica Vucicevic
Greenhorn

Joined: Jan 07, 2005
Posts: 10
It does not only depend on the type of the primitives but on the value they hold!
In your example the code compiles find and the result of a = 922.0
You would only have a problem as using 4398046511103 for example would result in lost precision.

I hope this answer will satisfy your need!

cheers!
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Stevica's analysis would be correct if a and l were final. Since they are not final, the compiler can not rely on the initial values and must consider all possible values.

The javac error message "possible loss of precision" is misleading because the rules on casting fom an integer type to a floating point type are based on magnitude, not precision. Java considers conversion from any integer type to any floating point to be a widening conversion not requiring an explicit cast because there may be a loss of precision but there is no loss of overall magnitude.

A float can easily hold the largest possible long. A long goes up to 2^63-1. A float can at least hold up to 2^127.

This is from section 5.1.2 of the Java Language Specification:
Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (�4.2.4).


Mike Gershman
SCJP 1.4, SCWCD in process
ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830


this is a simple diagram to remember .
note : when you are going left to right , you don't need to cast ( byte -> short => putting byte into short )
and if you are going right to left , then you need to cast .
[ January 19, 2005: Message edited by: rathi ji ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: doubt on casting