Skip to content

Loop Usage

Java Loops and When to Use Them

Difference For Loop While Loop Do-While Loop
Introduction For loops in Java iterate a given set of statements multiple times. The Java while loop executes a set of instructions until a boolean condigion is met. The do-while loop executes a set of statements at least once, even if the condition is not met. Afterthe first execution, it repeats the iteration until the boolean condition is met.
Best time to use Use it when you know the exact number of times to execute the part of the program. Use it when you don’t know how many times you want the iteration to repeat. Use it when you don’t know how many times you want the iteration to repeat, but it should execute at least one time.
Syntax for(; ; ) { /Repeated statements/ } while() { /Repeated statements/ } do { /Repeated statements/ } while( );
for( : ) { /Repeated statements/ }
Examples for(int i=0; i<=5; i++) int i=0; while( i<=5 ) int i=0; do { System.out.println(i); } while( i<=5 );
String[] strs = {“Hello”,”World”}; for(String s : strs){ /Repeated statements/ }