Reputation: 3538
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?
Upvotes: 2
Views: 173
Reputation: 393791
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
Upvotes: 3
Reputation: 121998
From 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.
Upvotes: 2