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效果一樣了。