While loop in Java
The while loop in Java loops forever as long as the condition is true. while loop saves time, easy to code, and makes code more readable.
Syntax
while(condition){ //code block to be executed }
Example
When you execute this sample code. It will loop forever as long as the condition is true.
while(true){ System.out.println("Java programming Language"); }
Here’s another example with while loop in Java. See the example code below.
int i = 1; while(i <= 5){ System.out.println(i+". Repeat"); i++; }
Output
1. Repeat 2. Repeat 3. Repeat 4. Repeat 5. Repeat
The example code above will execute the code and loop as long as the variable is less than 5. Don’t forget to increment the variable used. Otherwise, it will loop forever.
Do/while in Java
The do will be executed first before checking the condition. When the condition is false. The do will still run because it will run first. See the example code below.
int i = 1; do{ System.out.println(i+". Repeat"); i++; } while(i <= 5);
Output
1. Repeat 2. Repeat 3. Repeat 4. Repeat 5. Repeat
Always don’t forget to increment the variable. Otherwise, it will loop forever.
Another example with do/while
This example will show you the output with the false condition.
do{ System.out.print("Java Programming Language"); } while(false);
Output
Java Programming Language