14: goto 25
用 javap 测试程序,除了第二种情况下的 JUMP 指令外,我几乎看不出有什么不同。
如果您在 else 语句上没有要执行的内容,我看不到添加 else 的理由。您可能想使用它来进行日志记录等。
public class Test {
public static void main(String[] s){
if(testMethod()){
System.out.println("in if");
}
System.out.println("in else");
}
static boolean testMethod(){
return false;
}
}
导致
public static void main(java.lang.String[]);
Code:
Stack=2, Locals=1, Args_size=1
0: invokestatic #16; //Method testMethod:()Z
3: ifeq 14
6: getstatic #20; //Field java/lang/System.out:Ljava/io/PrintStream;
9: ldc #26; //String in if
11: invokevirtual #28; //Method java/io/PrintStream.println:
(Ljava/lang/String;)V
14: getstatic #20; //Field java/lang/System.out:Ljava/io/PrintStream;
17: ldc #34; //String in else
19: invokevirtual #28;
//Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
和
public class Test {
public static void main(String[] s){
if(testMethod()){
System.out.println("in if");
}else{
System.out.println("in else");
}
}
static boolean testMethod(){
return false;
}
}
会产生,
public static void main(java.lang.String[]);
Code:
Stack=2, Locals=1, Args_size=1
0: invokestatic #16; //Method testMethod:()Z
3: ifeq 17
6: getstatic #20; //Field java/lang/System.out:Ljava/io/PrintStream;
9: ldc #26; //String in if
11: invokevirtual #28; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
14: goto 25
17: getstatic #20; //Field java/lang/System.out:Ljava/io/PrintStream;
20: ldc #34; //String in else
22: invokevirtual #28; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25: return