Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wrappers

 
Fran Kindred
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
created test scenario


I expected line 6 and line 4 to fail but why does it work
 
Fran Kindred
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry guys I found the answer to this, constructor is overloaded to accept double. But why does it still accept float? implicit casting?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Float has 3 constructors. One takes a String argument and parses it. The second comstructor takes a float and the third takes a double.

In converting an integer type, the "Float(float value)" constructor will be invoked because it has the most restrictive parameter type that still accepts an integer type. float is more restrictive than double because a float argument will be accepted as a double parameter without an explicit cast, while a double argument will not be accepted as a float parameter without an explicit cast.

The concept of a widening cast has to do with the range of legal values, not precision. So any integer type can become a float as a widening conversion, no explicit cast required. It's true that a double would preserve more precision from an int or long, but Java only considers range.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic