Java Do While Loop

By | September 29, 2021

This loop will work when the number of iterations is not known and the code has to run at least once. This loop will execute the program a number of times until the condition is false.

The do-while loop will get executed at least once because the condition is checked after the first iteration at the end of the program block.

Syntax

do{  
//code to be executed  
}
while(condition);

Example

public class DoWhileExample {  
public static void main(String[] args) {  
    int i=1;  
    do{  
        System.out.println(i);  
    i++;  
    }while(i<=3);  
}  
}

Output

1
2
3

Infinitive do-while loop

This loop will execute infinite time if we pass the true condition. You can exit the infinite loop by pressing ctrl+c.

Vamware

Syntax

do{  
//code to be executed  
}
while(true);

Example

public class DoWhileExample2 {  
public static void main(String[] args) {  
    do{  
        System.out.println("infinitive do while loop");  
    }while(true);  
}  
}

Output

infinitive do while loop 
infinitive do while loop 
infinitive do while loop 
ctrl+c

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *