File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final variables and Conversions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "final variables and Conversions" Watch "final variables and Conversions" New topic

final variables and Conversions

Kunal Goel

Joined: Sep 08, 2002
Posts: 16
Please have a look at the following code snippets
int i= 22;
byte b=i;// compile time error, narrowing conversion, requires an
explicit cast //(byte) OK !!
final int i=22;
byte b=i;// compilation successful, bcos value of i is determinable
at compile time
// OK !!
final double d=7.9;
float f=d;//compilation error – same as 1
//hmmmmm…. still thinking
But look, d is final, if it works with integral data types then why it does
not work with floationg pt. data types.
Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
Case 3 illustrates what we call a "narrowing primitive conversion". As mentioned in the Ergnosis' unofficial JLS errata, the second edition of the JLS does not contain anything related to double-to-float conversion.
Moreover, as can be seen on the chart available at Conversions and Promotions, a cast is definitely needed to convert a double to a float.
Bottom line: The distinction between an int and a byte is definitely not comparable with the distinction that can be made between a float and a double due to the bytes representation (IEEE 754) of doubles and floats.

[Blog] [Blogroll] [My Reviews] My Linked In
Saniya Ansari
Ranch Hand

Joined: Sep 30, 2002
Posts: 48
Just to add to what is already explained. Simply the problem is not of integral and float type final variables. But you are assigning a double to a float variable. Double is 64 bit and float is 32 bit. You can't assign it without an explicit cast.

I agree. Here's the link:
subject: final variables and Conversions
It's not a secret anymore!