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?
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.
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 Object
s (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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With