良好的措施:
建立在其他兩個答案,我把代碼兩件在一個例子如下:
public class SO {
public static void main(String[] args){
int i=0,j=100;
// Either a terminating ; symbol or {} braces work to make an "empty loop body".
while (++i < --j) {}
System.out.println("The midpoint between 0 and 100 is " +i); // Midpoint is 50.
}
}
和
public class SO2 {
public static void main(String[] args){
int i=0,j=100;
// Either a terminating ; symbol or {} braces work to make an "empty loop body".
while (++i < --j) ;
System.out.println("The midpoint between 0 and 100 is " +i); // Midpoint is 50.
}
}
使用的javap -c我得到了以下的字節碼:
Compiled from "SO.java"
public class SO {
public SO();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: bipush 100
4: istore_2
5: iinc 1, 1
8: iload_1
9: iinc 2, -1
12: iload_2
13: if_icmpge 19
16: goto 5
19: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
22: new #3 // class java/lang/StringBuilder
25: dup
26: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
29: ldc #5 // String The midpoint between 0 and 100 is
31: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
34: iload_1
35: invokevirtual #7 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
38: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
41: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
44: return
}
和
Compiled from "SO2.java"
public class SO2 {
public SO2();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: bipush 100
4: istore_2
5: iinc 1, 1
8: iload_1
9: iinc 2, -1
12: iload_2
13: if_icmpge 19
16: goto 5
19: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
22: new #3 // class java/lang/StringBuilder
25: dup
26: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
29: ldc #5 // String The midpoint between 0 and 100 is
31: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
34: iload_1
35: invokevirtual #7 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
38: invokevirtual #8 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
41: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
44: return
}
他們出現相同的言下之意,無論您選擇哪種方式,編譯器實現它完全一樣的。
實際上我用的'{;}'看到塊,而且要知道,我真的打算把任何在該塊,並沒有只需要創建一個大括號後面的填充。儘管這是我自己的事情,並且從來沒有見過其他人這樣做。 – Cruncher