Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khác biệt giữa while loop và do-while loop trong Java?


While loop trong Java thực thi một hoặc nhiều câu lệnh sau khi test loop continuation condition ở đầu mỗi iteration. Do-while loop, tuy nhiên, test loop continuation condition sau khi iteration đầu tiên hoàn thành. Do đó, do-while loop đảm bảo một lần thực thi loop logic trong khi while loop không.

Ví dụ

public class WhileAndDoWhileLoop { 
    public static void main(String args[]) { 
        int i=5; 
        System.out.println("Test while Loop:"); 
        while(i < 5) { 
            System.out.println("Iteration: "+ ++i); 
        } 
        System.out.println("Test do-while Loop:"); 
        i=5; 
        do { 
            System.out.println("Iteration: "+ ++i); 
        } while(i < 5); 
    } 
}

Trong ví dụ trên, while loop statement sẽ không thực thi lần nào. Tuy nhiên, một iteration của do-while loop sẽ thực thi.

Kết quả

Test while Loop: Test do-while Loop: Iteration: 6