120 likes | 132 Views
This article explains the syntax and usage of the do statement in Java. It includes examples and a flowchart of a do loop.
E N D
The do Statement • A do statement has the following syntax: do { statement; } while ( condition ); • The statement is executed once initially, and then the condition is evaluated • The statement is executed repeatedly until the condition becomes false
statement true condition evaluated false Flowchart of a do Loop
The do Statement • An example of a do loop: int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2); Don’t forget this semicolon! • The body of a do loop executes at least once
The while Loop The do Loop condition evaluated statement true true false condition evaluated statement false Comparing while and do
animation Trace do Loop Initialize count int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. Print Welcome to Java int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. Increase count by 1 count is 1 now int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. (count < 2) is true int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. Print Welcome to Java int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. Increase count by 1 count is 2 now int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop, cont. (count < 2) is false since count is 2 now int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);
animation Trace do Loop The loop exits. Execute the next statement after the loop. int count = 0; do { System.out.println("Welcome to Java!"); count++; } while (count < 2);