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
.