Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

while

Example

In the example provided, the code within the loop will execute repeatedly as long as a variable ‘i’ remains less than 5.

int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}

Definition and Usage

The while loop iterates through a block of code while a specified condition remains true.

Note: Ensure to increment the variable utilized in the condition, or else the loop will perpetually continue, never reaching an end.

More Examples

The do/while loop, a variant of the while loop, executes the code block initially, checks the condition afterward, and then continues to repeat the loop as long as the condition remains true.

Example

int i = 0;
do {
  System.out.println(i);
  i++;
}  
while (i < 5);