Java while loop

Created with Sketch.

 

Java while loop

In Java, a while loop is used to execute statement(s) until a condition is true. In this tutorial, we learn to use it with examples. First of all, let’s discuss its syntax:

while (condition(s)) {
// Body of loop
}

1. If the condition(s) holds, then the body of the loop is executed after the execution of the loop body condition is tested again. If the condition still holds, then the body of the loop is executed again, and the process repeats until the condition(s) becomes false. The condition evaluates to true or false and if it’s a constant, for example, while (x) {…}, where x is a constant, then any non zero value of ‘x’ evaluates to true, and zero to false.

2. You can test multiple conditions such as

while (a > b && c != 0) {
// Loop body
}

Loop body is executed till value of variable a is greater than value of variable b and variable c isn’t equal to zero.

3. A body of a loop can contain more than one statement. For multiple statements, you need to place them in a block using {}. If the body contains only one statement, you can optionally use {}. It is always recommended to use braces to make your program easy to read and understand.

Java while loop example

Following program asks a user to input an integer and prints it until the user enter 0 (zero).

import java.util.Scanner;

class WhileLoop {
public static void main(String[] args) {
int n;

Scanner input = new Scanner(System.in);
System.out.println(“Input an integer”);

while ((n = input.nextInt()) != 0) {
System.out.println(“You entered “ + n);
System.out.println(“Input an integer”);
}

System.out.println(“Out of loop”);
}
}

Output of program:
Java while loop example program

 

Java while loop break program

We can write above program using a break statement. We test a user input and if it’s zero then we use “break” to exit or come out of the loop.

import java.util.Scanner;

class BreakWhileLoop {
public static void main(String[] args) {
int n;

Scanner input = new Scanner(System.in);

while (true) { // Condition in while loop is always true here
System.out.println(“Input an integer”);
n = input.nextInt();

if (n == 0) {
break;
}
System.out.println(“You entered “ + n);
}
}
}

Java while loop break continue program

import java.util.Scanner;

class BreakContinueWhileLoop {
public static void main(String[] args) {
int n;

Scanner input = new Scanner(System.in);

while (true) {
System.out.println(“Input an integer”);
n = input.nextInt();

if (n != 0) {
System.out.println(“You entered “ + n);
continue;
}
else {
break;
}
}
}
}

Continue statement takes control to the beginning of the loop, and the body of the loop executes again. Whatever you can do with a while loop can be done with a for loop or a do-while loop.

Leave a Reply

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