0

Directly from the javadoc:

s', 'S' general If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

Does it mean that in the following line of code the number 3 (arg) gets autoboxed in an Integer and then the method arg.toString() gets invoked?

 System.out.format("%10s",3);
Rollerball
  • 12,618
  • 23
  • 92
  • 161

2 Answers2

1

It does. All variadic arguments are autoboxed. And yes, toString() method is called.

Valeri Atamaniouk
  • 5,125
  • 2
  • 16
  • 18
1

You can check yourself what happens exactly by compiling a small test program, and then decompiling it with javap (a tool included with the JDK):

public class Example {
    public static void main(String[] args) {
        System.out.format("%10s",3);
    }
}

Compile this with javac Example.java and then decompile it with javap -c Example:

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

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #3                  // String %10s
       5: iconst_1
       6: anewarray     #4                  // class java/lang/Object
       9: dup
      10: iconst_0
      11: iconst_3
      12: invokestatic  #5                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      15: aastore
      16: invokevirtual #6                  // Method java/io/PrintStream.format:(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;
      19: pop
      20: return
}

You see what this does:

  • It creates an Object[] in which first the string "%10s" is stored (lines 3-10)
  • It calls Integer.valueOf() to box the value 3 (lines 11, 12)
  • The Integer object is stored in the array (line 15)
  • Then the method format(Object[]) is called (line 16)

Note: The array is used because the format method is a varargs method; varargs are implemented using arrays.

Jesper
  • 202,709
  • 46
  • 318
  • 350