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:变量声明和范围
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
