java - while 和 if 语句中无法访问代码

标签 java

以下代码自 x=3 起无法编译无法访问

while (false) { x=3; }

但是为什么for( int i = 0; i< 0; i++) {x = 3;}编译正常吗?在此代码中x=3也是无法访问的。

最佳答案

参见JLS 14.21, Unreachable Statements .

The contained statement [in a while loop] is reachable iff the while statement is reachable and the condition expression is not a constant expression whose value is false.

false是一个常量表达式,其值为 false ,所以x=3;无法访问。

The contained statement [in a basic for loop] is reachable iff the for statement is reachable and the condition expression is not a constant expression whose value is false.

i<0不是常量表达式,因此所包含的语句被认为是可访问的,即使它实际上不可访问。

关于java - while 和 if 语句中无法访问代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58797600/

相关文章:

java - 程序卡在 ObjectInputStream 构造函数处

java - 哪一行代码使我的 RSS 阅读器只读取底部标签?

java - 仅使用方法和二维数组的井字游戏java

Java 泛型绑定(bind)与原始类型不匹配

java - 匿名监听器是否与弱引用不兼容?

java - Java 中没有显式访问修饰符意味着什么?

java - 多次重新运行一组 JUnit 测试

java - 在 eclipse 中重新启动 GAE

java - CertPath 问题 - HTTPS 服务器不显示 CA 证书

java - 在现有 Spring with JSP 应用程序中使用 Spring MVC