Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can’t printf be formatted with an array of ints?

Tags:

java

I want to format an output string with a series of variables. When I use an array of strings, this works as expected:

String[] myArray = new String[3];
// fill array with strings
System.out.printf("1: %s \n2: %s \n3: %s\n", myArray);

I want to use this to print the results of simulated dice-throws, so I use an array of ints. However, this doesn’t work:

int[] myArray = new int[3];
// fill array with numbers
System.out.printf("1: %d \n2: %d \n3: %d\n", myArray);
Exception in thread "main" java.util.IllegalFormatConversionException: d != [I

Of course, I could use myArray[0] etc. for every element, but this doesn’t seem very elegant.

Why is this so and how can I achieve the desired result?

like image 437
msch Avatar asked Dec 28 '22 00:12

msch


2 Answers

printf is a variable argument method that takes a String (the format string) and an arbitrary number of arguments (to be formatted).

Varargs are implemented as arrays in Java. printf expects Object as its varargs type, therefore the internal type is Object[].

A String[] is-a Object[] (i.e. it can be cast to that type), so the elements of the String[] will be interpreted as the separate arguments.

An int[] however, can't be cast to an Object[] so the int[] itself will be the first (and only) element of the varargs array.

Then you try to format the int[] using %d which won't work, because an int[] is not a (single) decimal number.

like image 89
Joachim Sauer Avatar answered Dec 30 '22 13:12

Joachim Sauer


This is because String is a reference type (i.e. subclass of Object) while int is a primitive type. The printf method expects an array of Objects (actually variable length argument list), and so a String[] fits in fine. Whenever you pass in a int[], since int is not an Object but int[] is, it takes the whole int[] as a single object and considers that a single argument.

like image 43
MAK Avatar answered Dec 30 '22 15:12

MAK