- Java Programming Basics
- Java Tutorial
- Java Environment Setup
- Java Separators
- Java Data Types
- Java Variables
- Java Variable Scope
- Java Type Casting
- Java Operators
- Java Increment Decrement
- Java Left Shift
- Java Right Shift
- Java Bitwise Operators
- Java Ternary Operator
- Java Control Statements
- Java if-else statement
- Java for Loop
- Java while Loop
- Java do-while Loop
- Java switch Statement
- Java break Statement
- Java continue Statement
- Java Popular Topics
- Java Arrays
- Java Multidimensional Array
- Java Strings
- Java Methods
- Java Date and Time
- Java Exception Handling
- Java File Handling
- Java OOP
- Java Classes and Objects
- Java Constructors
- Java Constructor Overloading
- Java Object as Parameter
- Java Returning Objects
- Java Encapsulation
- Java Abstraction
- Java Inheritance
- Java Polymorphism
- Java Packages
- Java Import Statement
- Java Multithreading
- Java Suspend Resume Stop Thread
- Java Programming Examples
- Java Programming Examples
while loop in Java with examples
In Java, a "while" loop is a control flow statement that lets you run a block of code over and over again as long as a certain condition holds true.
Java while loop syntax
The general form for using a "while" loop in Java is as follows:
while (condition) {
// code to continue its execution
// until the given "condition" is true.
}
In this case, "condition" is the expression that is evaluated before each loop iteration. If condition is true, the code inside the block is executed. This process is repeated until the condition is met, at which point the loop ends and program control returns to the statement following the "while" loop. As an example:
public class WhileLoopExample { public static void main(String[] args) { int i = 1; while (i <= 5) { System.out.println(i); i++; } } }
1 2 3 4 5
The program sets the variable "i" to 1. With the condition "i <= 5," the program enters a "while" loop. This means that the loop will keep running as long as "i" is less than or equal to 5.
The program prints the value of "i" within the loop using the "System.out.println()" method. The program increases "i" by one using the "i++" statement.
The program checks the loop condition "i <= 5" after each iteration of the loop. If the condition is true, the loop continues to execute; otherwise, the loop terminates.
Java while loop example
I already mentioned one example right above this section. But I'm willing to include a few more examples demonstrating the "while" loop in Java.
import java.util.Scanner; public class WhileLoopExample { public static void main(String[] args) { Scanner input = new Scanner(System.in); int count = 0; System.out.print("How many even numbers do you want to print? "); int n = input.nextInt(); System.out.println("\nList of first " + n + " even numbers:"); int i = 0; while (count < n) { if (i % 2 == 0) { System.out.print(i + " "); count++; } i++; } } }
How many even numbers do you want to print? 6 List of first 6 even numbers: 0 2 4 6 8 10
When we run the Java program you provided, it will ask the user for a number n and then print the first n even numbers in the same way as shown in the above output.
0 is regarded as an even number. An even number is any integer that is divisible by two, and 0 is an even number because 0 divided by two equals 0 with no remainder. As a result, in mathematics, 0 is classified as an even number.
Following is the step-by-step explanation of the above Java program demonstrating the "while" loop.
- The "Scanner" class from the "java.util" package is imported and used to read user input from the console.
- To read user input, the program creates a new "Scanner" object called "input."
- The program sets the integer variable "count" to 0. This variable will be used to count the number of even numbers printed thus far.
- To print "n" even numbers, the program prompts the user to enter the value of "n" using the output message: "How many even numbers do you want to print?"
- The program reads the user input and stores it in the integer variable "n" using the Scanner class's "nextInt()" method.
- The program sets the integer variable "i" to 0. The even numbers will be generated using this variable.
- With the condition "count < n," the program enters a "while" loop. This means that the loop will keep running as long as the "count" is less than "n."
- The program checks whether "i" is an even number within the loop using an "if" statement. If "i" is an even number (i.e., i % 2 == 0), the program prints its value and increments the "count" by one. If "i" is not an even number, the program simply increases "i" by one and skips the rest of the loop body.
- The program increases "i" by one after each loop iteration.
- The loop is terminated when "count" equals "n."
- Finally, the program prints, separated by spaces, a list of the even numbers generated during the loop.
Here is another example that finds and prints the factorial of a given number using the "while" loop.
import java.util.Scanner; public class FactorialCalculator { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a positive integer: "); int num = input.nextInt(); int factorial = 1; int i = 1; while (i <= num) { factorial *= i; i++; } System.out.println("The factorial of " + num + " is " + factorial + "."); } }
Enter a positive integer: 6 The factorial of 6 is 720.
Before we wrap up our discussion of the "while" loop, here's a program that counts down from 10, printing exactly 10 lines of "tick":
public class JavaProgram { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n--; } } }
When the above Java program is compiled and executed, it will produce the following output:
« Previous Tutorial Next Tutorial »