为什么Java只在while循环中识别不可访问的代码?
如果我有这样的代码为什么Java只在while循环中识别不可访问的代码?,java,loops,if-statement,unreachable-code,Java,Loops,If Statement,Unreachable Code,如果我有这样的代码 public static void main(String args[]){ int x = 0; while (false) { x=3; } //will not compile } public static void main(String args[]){ int x = 0; if (false) { x=3; } for( int i = 0; i< 0; i++) x = 3; } 编译器会抱怨x
public static void main(String args[]){
int x = 0;
while (false) { x=3; } //will not compile
}
public static void main(String args[]){
int x = 0;
if (false) { x=3; }
for( int i = 0; i< 0; i++) x = 3;
}
编译器会抱怨x=3
是不可访问的代码,但如果我有这样的代码
public static void main(String args[]){
int x = 0;
while (false) { x=3; } //will not compile
}
public static void main(String args[]){
int x = 0;
if (false) { x=3; }
for( int i = 0; i< 0; i++) x = 3;
}
publicstaticvoidmain(字符串参数[]){
int x=0;
如果(false){x=3;}
对于(inti=0;i<0;i++)x=3;
}
然后,尽管无法访问
if语句
和for循环
中的代码,但它仍能正确编译。为什么java工作流逻辑没有检测到这种冗余?任何用例?带有if条件的用例正在调试。AFAIK规范明确允许if
-语句(不用于循环)允许这样的代码:
class A {
final boolean debug = false;
void foo() {
if (debug) {
System.out.println("bar!");
}
...
}
}
您可以稍后(或在运行时通过调试器)更改debug
的值以获得输出
编辑
正如Christian在评论中指出的,可以找到一个链接到规范的答案。如中所述,此功能保留用于“条件编译”
JLS中描述的一个示例是,您可能有一个常数
static final boolean DEBUG = false;
以及使用这个常数的代码
if (DEBUG) { x=3; }
其思想是提供一种可能性,可以轻松地将
DEBUG
从true
更改为false
,而无需对代码进行任何其他更改,如果上述代码出现编译错误,这是不可能的 关于for循环,我认为它只是不像while循环中使用false
常量那样容易检测
关于if
,为了能够在编译时从字节码中删除调试代码,故意选择对其进行授权:
private static final boolean DEBUG = false; // or true
...
if (DEBUG) {
...
}
+1用于JLS参考。感谢这有意义。奇怪的是,
if(false){x=3;}
部分看起来好像是从中复制的(一直滚动到底)。啊。我在OCJP认证演示考试中遇到了这个问题。谢谢你的JSL链接。好吧,我想写这个演示的其中一个家伙很懒…:)