Java switch : variable declaration and scope(Java switch:变量声明和范围)
问题描述
Java 编译器如何处理下面的 switch 块?'b' 变量的作用域是什么?
How does the Java compiler handle the following switch block ? What is the scope of the 'b' variable ?
请注意,b"变量仅在 switch 语句的第一个分支中声明.尝试在第二个分支中声明它也会导致重复的局部变量"编译错误.
Note that the 'b' variable is declared only in the first branch of the switch statement. Attempting to declare it in the second branch as well results in a "duplicate local variable" compilation error.
int a = 3;
switch( a ) {
case 0:
int b = 1;
System.out.println("case 0: b = " + b);
break;
case 1:
// the following line does not compile: b may not have been initialized
// System.out.println("case 1 before: b = " + b);
b = 2;
System.out.println("case 1 after: b = " + b);
break;
default:
b = 7;
System.out.println("default: b = " + b);
}
注意:以上代码使用 java 1.6 编译器编译.
Note: the above code compiles with a java 1.6 compiler.
推荐答案
范围和往常一样,由 {
和 }
分隔.
The scope is, just as usual, delimited by {
and }
.
这篇关于Java switch:变量声明和范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java switch:变量声明和范围


基础教程推荐
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01