0

Float is an object, float is a variable. And how to a float can assign with a Float. Thank you!

Float F = new Float(3);
float f = F;
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
sonas sonas
  • 197
  • 1
  • 5
  • 15

2 Answers2

5

That's called autoboxing/unboxing. It's a Java feature which allows implicit conversions between primitive types and their corresponding wrapper classes.

Autoboxing is when, like in your snippet, a primitive is wrapped into an object. Unboxing, viceversa, is the opposite way.

What happens under the hood is something like:

float f = 10.0f;
Float fo = new Float(f); // autoboxing
float f2 = fo.floatValue(); // unboxing
Jack
  • 131,802
  • 30
  • 241
  • 343
  • Autoboxing doesn't work by converting it to `new Float(...)`, but to `Float.valueOf(...)`. – Jesper Dec 28 '13 at 18:57
  • @Jesper which is `new Float(f)`, check implementation: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Float.java#Float.valueOf%28float%29 – Jack Dec 28 '13 at 18:59
  • Yes, but for `Integer` for example, `Integer.valueOf()` does not do `new Integer()` - it has a cache for `Integer` objects with values between -128 and 127. – Jesper Dec 29 '13 at 21:29
2

The F object of type Float is automatically unboxed. What you have in your f variable isn't F but F.floatValue().

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758