java - 为什么我们必须在 Java 中的 if 语句之外声明变量
问题描述
在 Java 中,如果我们运行:
public class HelloWorld{
public static void main(String []args){
if (true) {
int test = 1;
} else {
int test = 2;
}
System.out.println(test);
}
}
它会抛出:
HelloWorld.java:9: error: cannot find symbol
System.out.println(test);
^
symbol: variable test
location: class HelloWorld
1 error
但是,在 php 中,如果我们运行:
<?php
//Enter your code here, enjoy!
if (true) {
$test = 1;
} else {
$test = 2;
}
echo $test;
它将打印 1。
我怀疑这是否是因为 Java 是强类型语言而 php 是弱类型语言。有人可以给出更深层次和更低层次的解释吗?
解决方案
在 Java 中,变量的可见范围受限于{}
if (true) {
int test = 1;
} else {
int test = 2;
}
System.out.println(test);// Will fail to compile
同样重要的是要注意如下所示的死代码:
int test;
if (true) {
test = 1;
} else {
test = 2;// Dead code
}
System.out.println(test);
因为块永远不会被执行导致if (true)
成为死代码。else
test = 2
推荐阅读
- installation - 当我调用 apt-get install llvm 时会发生什么?
- c# - 如何知道组合框是否绑定?
- ios - Swift 类未从情节提要中正确加载
- javascript - 任何允许在网站上发布收到的 WhatsApp 消息的 API 或其他东西
- angular - Angular 5 上的单元测试 http 服务
- c# - C# 使用 CSV 标头为不同的变量赋值
- android - 未观察到多次调用设置 LiveData
- sharepoint - sharepoint 2010 使用 API 获取文件的 ACL
- javascript - Bower 安装不创建 bower_components 文件夹
- javascript - Chart.js 如何对齐条形图中的两个 X 轴?