-6

I have this code,

class Test
{
    public static void  main(String args[])
    {
        String x = "Hello";
        String y = "Bye!";
        System.out.printf("This is %s, this is %s", x);
    }
}

And the the java compiler compiled it, but it obviously has an error. My question is, why didn't the compiler catch this error? Where's the benefit of static typing if it can't even catch this small mistake?

4

3 回答 3

7

printf()将 String 和 Objects 的 vararg 数组作为参数。您的程序传递符合这些参数类型的参数,因此编译器很高兴。

例如,如果您这样做,编译器会拒绝您的方法调用

Integer a = 23;
System.out.printf(a, x);

因为整数不是字符串。

您似乎认为静态类型使运行时错误成为不可能。根本不是这样。编译器不知道 printf() 的作用以及它们%s在字符串中的含义。它不知道数量%s应该与传递给方法的参数数量相匹配。即使是这样,您也可以将 String 类型的变量和 Object[] 类型的变量传递给该方法,其长度和值仅在运行时知道,而不是在编译时知道。例如:

String s = readPatternFromUser();
Object o = readFirstArgFromUser();
System.out.print(s, o);
于 2013-08-31T14:02:56.630 回答
1

因为错误是运行时错误,而不是编译时错误。两个 %s 的字符串替换发生在运行时。编译器不知道您“缺少” y 参数。

于 2013-08-31T14:03:34.223 回答
0

传递给 printf() 方法的(静态)类型是正确的 - 这是一个非法参数,直到运行时才被发现。

Integer.parseInt("foo")这与将正确类型的不合适值传递给方法的无数其他情况没有什么不同。

于 2013-08-31T14:03:49.350 回答