Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who will do the Auto-boxing/unboxing?

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.

like image 233
glee8e Avatar asked Jan 28 '16 07:01

glee8e


1 Answers

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.

like image 193
Maroun Avatar answered Sep 22 '22 08:09

Maroun