Who will do the Auto-boxing/unboxing?
Asked Answered
D

1

7

Is it the compiler or the runtime do the auto-boxing/unboxing?

Consider the following example:

public Integer get() {
    return 1;  //(1)
}

At (1), the primitive integer value will be converted into something like new Integer(1), and returned. That's effectively some kind of implict consverion known as auto-boxing , but who will do that? The compiler, or the JVM?

I was just starting to learn the ASM, and such boxing issue really confuse me.

Dosser answered 28/1, 2016 at 7:30 Comment(2)
consider this: int a = myScan.nextInt(); Integer b = a; how will the compiler do this, without being able to know what value a will have?Aborticide
@Aborticide The compiler will to Integer b = Integer.valueOf(a);. Simple. It doesn't need to know the value of a. See also the accepted answer to this question.Applicable
S
12

You can see the disassembled code using the javap -c command:

public class Example {
  public Example();
    Code:
       0: aload_0
       1: invokespecial #1    // Method java/lang/Object."<init>":()V
       4: return

  public java.lang.Integer get();
    Code:
       0: iconst_1
       1: invokestatic  #2   // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       4: areturn
}

You can see that the Integer#valueOf was invoked, so the actual code gets translated to:

public Integer get(){
    return Integer.valueOf(1);
}

Conclusion:

The compiler does it for you.

Schild answered 28/1, 2016 at 7:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.