The first does not compile (you got an error), the second compiles (you just got a warning). That’s the difference.
As to why Eclipse detects dead code, well, that’s just the convenience of an integrated development tool with a built-in compiler which can be finetuned more as opposed to JDK to detect this kind of code.
Update: the JDK actually eliminates dead code.
public class Test {
public void foo() {
System.out.println("foo");
if(true)return;
System.out.println("foo");
}
public void bar() {
System.out.println("bar");
if(false)return;
System.out.println("bar");
}
}
javap -c
says:
public class Test extends java.lang.Object{ public Test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: return public void foo(); Code: 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3; //String foo 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/StrV 8: return public void bar(); Code: 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #5; //String bar 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 11: ldc #5; //String bar 13: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 16: return }
As to why it (Sun) doesn’t give a warning about that, I have no idea 🙂 At least the JDK compiler has actually DCE (Dead Code Elimination) builtin.