【笔记】java for循环执行顺序

for循环很简单,用起来也很方便,但对for循环的执行顺序并不了解。

举个例子:

public class TestOrder {

    static boolean order(char c) {
        System.out.print(c);
        return true;
    }
    
    public static void main(String[] args) {
        int i = 0;
        for (order('A'); order('B') && (i < 2); order('C')) {
            i++;
            order('D');
        }
    }
}

以上这段代码,它的执行结果是什么呢???

实际的执行结果是:ABDCBDCB;

由此可见,for循环并不是在执行完条件之后,再一遍一遍地去执行循环代码块。

for(int i = 0; i < 3 ; i++){
//do some thing
}

其实可以转换成

int i = 0 ;
while(i < 3 ){
    //do some thing;
    i++  
}

PS:注意,虽然可以这样理解没错,但还是要注意作用域的范围。

无论执行顺序是什么,i都只能在for循环内有用。

原文地址:https://www.cnblogs.com/nonkicat/p/2680392.html