Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variables and Conversions

 
Kunal Goel
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please have a look at the following code snippets
(1)
int i= 22;
byte b=i;// compile time error, narrowing conversion, requires an
explicit cast //(byte) OK !!
(2)
final int i=22;
byte b=i;// compilation successful, bcos value of i is determinable
at compile time
// OK !!
(3)
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
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saniya Ansari
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic