return中断方法和Unreachable code(永远达不到的代码)
1.下面这段代码因为for循环是个死循环,System.out.println(); 执行不到编辑器会报错Unreachable code(永远达不到的代码)
public static void main(String[] args) {for(;;) {}System.out.println();//此处报错:Unreachable code(永远达不到的代码)}
2.下面这段代码中的return会中断方法
public class Test3 {public static void m1() {for (int i = 1; i <= 10; i++) {System.out.println(i);if (i == 2) {return ;//此处中断此方法}}System.out.println("hello world!!!");//这行执行不到}public static void main(String[] args) {m1();}
}
上面两段代码都出现了执行不到的代码,为什么一个报错,一个不报错?
第二段代码不报错是因为编辑器没有那么智能,编辑器会认为 System.out.println(“hello world!!!”); 还是有可能执行到的