java中虽然goto是关键字,但是没有使用。而是重新定义了一种实现方式:标签
我在项目中还从来没有使用过,不过有的公司面试会问这个问题。当然这样的公司是垃圾公司的面大。
标签 的使用说明:
1、程序中可以有相同名称的标签。
2、标签和含有break语句的块语句之间不能有其他程序
out_label:
//System.out.println("hahah");此行如不注释编译不通过
for(int index = 0 ; index < 10; ++index){}
3、标签不仅仅能用于循环语句,if语句,代码块都可以使用。(如下例所示)
public class BreakLabelTest {
public static void main(String[] args) {
//测试带有Label的break语句
out_label:
//System.out.println("hahah");此行如不注释编译不通过
for(int index = 0 ; index < 10; ++index){
System.out.println("index = " + index );
for(int innerIndex = 0 ; innerIndex < 10;++innerIndex){
System.out.println("innerIndex = " + innerIndex);
if(innerIndex == 5){
break out_label;
}
}
}
int start = 5;
pre_label:
if(true){
System.out.println(start);
++start ;
if(start > 5){
break pre_label;
}
}
pre_label:
{
int first = 0;
int second = 2;
System.out.println("first = " + first);
System.out.println("second = " + second);
break pre_label;
}
System.out.println("程序结束了!");
}
}