带有标签的break语句

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("程序结束了!");
 }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值