When does autoboxing take place exactly?
Asked Answered
U

1

6

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.

Ubiquitous answered 21/5, 2014 at 13:21 Comment(0)
G
9

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.

Greiner answered 21/5, 2014 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.