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 Loop

Loops

Loops execute a block of code until a certain condition is met.

They are advantageous for saving time, minimizing errors, and enhancing code readability.

Java While Loop

The while loop iterates through a code block as long as a specified condition remains true:

Syntax

while (condition) {
  // code block to be executed
}

In the following example, the code within the loop will iterate continuously as long as a variable (i) remains less than 5.

Example

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

 

Reminder: Ensure to increment the variable used in the condition; otherwise, the loop will continue indefinitely.