Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
其中';这是静态类型的好处,也就是为什么没有';你没抓到吗?JAVA_Java - Fatal编程技术网

其中';这是静态类型的好处,也就是为什么没有';你没抓到吗?JAVA

其中';这是静态类型的好处,也就是为什么没有';你没抓到吗?JAVA,java,Java,我有这个密码 class Test { public static void main(String args[]) { String x = "Hello"; String y = "Bye!"; System.out.printf("This is %s, this is %s", x); } } java编译器编译了它,但它显然有一个错误。我的问题是,为什么编译器没有捕捉到这个错误?如果静态类型连这个小错误都抓不住

我有这个密码

class Test
{
    public static void  main(String args[])
    {
        String x = "Hello";
        String y = "Bye!";
        System.out.printf("This is %s, this is %s", x);
    }
}
java编译器编译了它,但它显然有一个错误。我的问题是,为什么编译器没有捕捉到这个错误?如果静态类型连这个小错误都抓不住,它的好处何在?

printf()
将一个字符串和一个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);
因为该错误是运行时错误,而不是编译时错误。两个%s的字符串替换在运行时发生。编译器不知道您“缺少”了y参数。

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


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

但是我的程序不符合,因为字符串说它将有两个替换,而我只给出了一个。编译器没有看到或关心吗?@edgararroutiounian
printf
是一种方法,而不是编译时替换。字符串值不会被解释/编译/评估为Java代码。他们只是。。。字符串值。谢谢,那么运行时/编译时的区别是什么呢?可能最好只使用google/wiki,因为它非常重要。不建议从SO评论中学习这些内容。:)@Edgararroutiounian:就是它的意思:运行时=程序运行或执行时。编译时间=编译源代码时。此处不执行静态类型检查,如果需要,请使用StringBuilder。