⬅ Previous Topic
Java default KeywordNext Topic ⮕
Java double Keyword⬅ Previous Topic
Java default KeywordNext Topic ⮕
Java double Keyworddo
Keyword in Java
In Java, the do
keyword is part of the do-while loop, a control flow statement that allows a block of code to execute at least once, and then repeatedly based on a given condition.
This structure is unique because it checks the loop condition after executing the loop body. That means even if the condition is false at the start, the loop will run once — guaranteed.
do
Keyworddo {
// statements
} while (condition);
do { }
executes first.while
clause.true
, the loop runs again. If false
, the loop ends.This example prints numbers from 1 to 5 using the do
keyword.
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Number: " + i);
i++;
} while (i <= 5);
}
}
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
- The variable i
starts at 1.
- The loop runs and prints the number.
- After printing, i
is incremented.
- The condition (i <= 5)
is checked after the block executes.
Let’s see what happens when the condition is false to begin with.
public class DoWhileOnce {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("This will run even if condition is false!");
} while (i < 5);
}
}
This will run even if condition is false!
Although i
is 10 and the condition i < 5
is clearly false, the loop body runs once before the condition is checked. That’s the defining behavior of a do-while
loop.
This example keeps asking for input until the user types 'exit'.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input;
do {
System.out.print("Enter a command (type 'exit' to quit): ");
input = scanner.nextLine();
} while (!input.equalsIgnoreCase("exit"));
System.out.println("Program ended.");
}
}
Enter a command (type 'exit' to quit): hello
Enter a command (type 'exit' to quit): test
Enter a command (type 'exit' to quit): exit
Program ended.
do-while
when the block must execute at least once.do-while
loops.while
LoopFeature | while |
do-while |
---|---|---|
Condition checked | Before executing block | After executing block |
Guaranteed execution? | No | Yes (at least once) |
⬅ Previous Topic
Java default KeywordNext Topic ⮕
Java double KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.