break
break可用于循环和switch...case...语句中。
用于switch...case中:
执行完满足case条件的内容内后结束switch,不执行下面的语句。
eg:
public static void breakSwitch1() {
int n = 1;
switch (n) {
case 1:
System.out.println("this is one.");
break;
case 2:
System.out.println("this is two.");
break;
default:
System.out.println("Others.");
}
}
结果:
this is one.
eg2:
public static void breakSwitch2() {
int n = 1;
switch (n) {
case 1:
System.out.println("this is one.");
//break;
case 2:
System.out.println("this is two.");
break;
default:
System.out.println("Others.");
}
}
结果:
this is one.
this is two.
如果不使用break语句则所有的操作将在第一个满足条件之后的语句全部输出,直到遇到break语句为止;
一、作用和区别
break的作用是跳出当前循环块(for、while、do while)或程序块(switch)。在循环块中的作用是跳出当前正在循环的循环体。在程序块中的作用是中断和下一个case条件的比较。
continue用于结束循环体中其后语句的执行,并跳回循环程序块的开头执行下一次循环,而不是立刻中断该循环体。
- 当循环执行到break语句时,就退出整个循环,然后执行循环外的语句。
当循环语句执行到continue时,当次循环结束,重新开始下一轮循环。如果已经是最后一轮循环了,那么这是的continue就与break效果一样了。