printf()
takes a String and a vararg array of Objects as argument. Your program passes arguments that conform to these argument types, so the compiler is happy.
The compiler would reject your method call if you did, for example
Integer a = 23;
System.out.printf(a, x);
because an Integer is not a String.
It seems like you think static typing makes runtime errors impossible. That’s not the case at all. The compiler doesn’t know what printf() does and what those %s
mean in the String. It doesn’t know that the number of %s
is supposed to match the number of arguments passed to the method. And even if it did, you could pass a variable of type String, and a variable of type Object[] to the method, whose length and values are only known at runtime, and not at compile time. For example:
String s = readPatternFromUser();
Object o = readFirstArgFromUser();
System.out.print(s, o);
3
solved Where’s the benefit of static typing, aka why wasn’t this caught? Java