简体   繁体   中英

Integer in System.out.println - unboxing or toString()?

I have pretty simple question.

I write code snippet like this one:

Integer integer = new Integer(42);
System.out.println(integer);

The question is what took place here?

  • Automatic unboxing Integer to privitive int value, or
  • Integer's toString() method was invoked?

Well, since the method overloading resolution process has 3 phases, and the initial phase doesn't do boxing/unboxing to match the arguments to the candidate methods, the PrintStream method being called here should be public void println(Object x) , since Integer is an Object .

void println(Object x) calls String.valueOf(Object) , which calls Integer 's toString() .

Byte code :

     0: new           #16                 // class java/lang/Integer
     3: dup
     4: bipush        42
     6: invokespecial #18                 // Method java/lang/Integer."<init>":(I)V
     9: astore_1
    10: getstatic     #21                 // Field java/lang/System.out:Ljava/io/PrintStream;
    13: aload_1
    14: invokevirtual #27                 // -->  Method java/io/PrintStream.println:(Ljava/lang/Object;)V
    17: return

From JLS # 15.12.2. Compile-Time Step 2: Determine Method Signature JLS # 15.12.2. Compile-Time Step 2: Determine Method Signature

The first phase (§15.12.2.2) performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

Hence no unboxing performed and chosen the Object param method.

Integer's toString() method was invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM