Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java do Keyword
Usage and Examples



do 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.

Syntax of the do Keyword

do {
  // statements
} while (condition);

How It Works

Example 1: Basic do-while Loop

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

Explanation

- 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.

Example 2: do-while Runs Even If Condition Is False

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!

Explanation

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.

Common Use Cases

Example 3: Input Until User Types 'exit'

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.

Best Practices

Comparison with while Loop

Feature while do-while
Condition checked Before executing block After executing block
Guaranteed execution? No Yes (at least once)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You 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.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M