Consider the following toy method:
public Float testReturnFloat() {
return 2f;
}
And the following client code:
float resultOne = testReturnFloat();
Float resultTwo = testReturnFloat();
Do now both calls involve autoboxing, or only the latter, even though Float testReturnFloat()
has been used as method signature?
Small note: This question is only for theoretical analysis, I encountered it as I almost put this into production code due to a typo.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.
Autoboxing and unboxing are introduced in Java 1.5 to automatically convert the primitive type into boxed primitive( Object or Wrapper class).
Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.
testReturnFloat()
itself involves autoboxing because the primitive float 2f
is implicitly converted to a Float
before it's returned. Now when you write
float resultOne = testReturnFloat();
the result is again unboxed to produce a primitive float
which is then assigned to resultOne
.
When you write
Float resultTwo = testReturnFloat();
nothing special happens. The Float
returned by testReturnFloat()
is assigned to resultTwo
.
Really the best way to understand this is to look at the bytecode. Here's the bytecode for testReturnFloat()
:
public java.lang.Float testReturnFloat();
Code:
0: fconst_2
1: invokestatic #57 // Method java/lang/Float.valueOf:(F)Ljava/lang/Float;
4: areturn
As you can see, Float.valueOf()
is invoked on 2f
(fconst_2
). This is the autoboxing I was talking about.
Now for your client code:
float resultOne = testReturnFloat();
becomes
0: invokestatic #16 // Method testReturnFloat:()Ljava/lang/Float;
3: invokevirtual #20 // Method java/lang/Float.floatValue:()F
6: fstore_1
Notice that unboxing occurs via Float#floatValue()
.
Finally,
Float resultTwo = testReturnFloat();
becomes
7: invokestatic #16 // Method testReturnFloat:()Ljava/lang/Float;
10: astore_2
As I said, nothing special; the return value of testReturnFloat()
is just stored in resultTwo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With