一、概述
有時候,細節決定成敗。
二、代碼文件(Test.java)
兩個for循環,一個是++i,另一個是j++。
public class Test {
public static void main(String[] args) {
int count = 10;
System.out.println("======第一個for循環輸出i的結果======");
for(int i = 0; i < count; ++i) {
System.out.println("i = " + i);
}
System.out.println("======第二個for循環輸出j的結果======");
for(int j = 0; j < count; j++) {
System.out.println("j = " + j);
}
}
}
三、輸出結果(相同)
======第一個for循環輸出i的結果======
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
======第二個for循環輸出j的結果======
j = 0
j = 1
j = 2
j = 3
j = 4
j = 5
j = 6
j = 7
j = 8
j = 9
四、編譯文件(Test.class)
編譯後打開同名的.class文件,展示如下。
public class Test {
public Test() {
}
public static void main(String[] args) {
int count = 10;
System.out.println("======第一個for循環輸出i的結果======");
int j;
for(j = 0; j < count; ++j) {
System.out.println("i = " + j);
}
System.out.println("======第二個for循環輸出j的結果======");
for(j = 0; j < count; ++j) {
System.out.println("j = " + j);
}
}
}
五、總結
在這種場景下,++i和j++輸出的結果一樣,但是編譯後的結果全是++j。
平時大部分人習慣性的寫爲j++,java源碼大部分是++j。
Copyright © 2018 Ansel. All rights reserved.