Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue

JK 2010 
Created at
Updated at  
7,814 0 0

Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code more readable.


Java While Loop

The while loop loops through a block of code as long as a specified condition is true:

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

In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

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

 


The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

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

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

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

 


Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

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

 

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has been executed.

 

Another Example

This example will only print even values between 0 and 10:

for (int i = 0; i <= 10; i = i + 2) {
  System.out.println(i);
}

Nested Loops

It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

// Outer loop
for (int i = 1; i <= 2; i++) {
  System.out.println("Outer: " + i); // Executes 2 times
  
  // Inner loop
  for (int j = 1; j <= 3; j++) {
    System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
  }
} 

For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in an array:

for (type variableName : arrayName) {
  // code block to be executed
}

The following example outputs all elements in the cars array, using a "for-each" loop:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example stops the loop when i is equal to 4:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}

Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}

Break and Continue in While Loop

You can also use break and continue in while loops:

Break Example

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
  if (i == 4) {
    break;
  }
}

Continue Example

int i = 0;
while (i < 10) {
  if (i == 4) {
    i++;
    continue;
  }
  System.out.println(i);
  i++;
}

 

Tags Do While Loop For Loop Java Java Do While Loop Java For Loop Java For-Each Loop Java Nested Loop Java While Loop Nested Loop.For-Each Loop break continue Facebook X
Comments 0
Similar posts
  1. Java Switch Statements
    7,378
  2. Java Short Hand If...Else (Ternary Operator)
    7,546
  3. Java If ... Else
    7,368
  4. Java Methods
    7,062
  5. Java Math
    7,409
  6. Java Scope
    7,074
  7. Java Variables
    7,426
  8. Java Recursion
    7,182
  9. Java Comments
    7,965
  10. The Print() Method
    7,136
  11. Java Syntax
    7,413
  12. Java Classes and Objects
    7,061
  13. Java Getting Started
    7,383
  14. Java Packages
    7,159
  15. Java Inheritance (Subclass and Superclass)
    7,162
  16. Java Polymorphism
    7,036
  17. Java Inner Classes
    7,027
  18. What is Java?
    7,074
  19. Python While Loops/For Loops
    7,469
  20. Machine Learning Types and Programming Languages
    7,214
  21. Java Tutorials associated with AP Computer Science A
    7,562
  22. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,150
  23. Java Servlet Example
    7,102
  24. Difference between Java and Javascript
    7,574
  25. Challenge: One Code Problem Per Day
    1,049
  1. Java Servlet Example
    7,102
  2. How do I replace content that based on the HTML UI Template
    7,138
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,150
  4. Dataset of California Foodbanks
    7,152
  5. Java Tutorials associated with AP Computer Science A
    7,562
  6. Java Inner Classes
    7,027
  7. Java Polymorphism
    7,036
  8. Java Inheritance (Subclass and Superclass)
    7,162
  9. Java Packages
    7,159
  10. Java Abstract Classes and Methods
    7,676
  11. Java Classes and Objects
    7,061
  12. Java Recursion
    7,182
  13. Java Scope
    7,074
  14. Java Methods
    7,062
  15. Java Arrays
    8,627
  16. Java Switch Statements
    7,378
  17. Java Short Hand If...Else (Ternary Operator)
    7,546
  18. Java If ... Else
    7,368
  19. Java Math
    7,409
  20. Java Variables
    7,426
  21. Java Comments
    7,965
  22. The Print() Method
    7,136
  23. Java Syntax
    7,413
  24. Java Getting Started
    7,383
  25. What is Java?
    7,074
Recently updated
  1. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    84
  2. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    205
  3. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    182
  4. The Evolution and Production Reality of Agentic AI
    174
  5. How to Activate or Waive Your UIUC Student Health Insurance
    253
  6. Complete Guide to Building a Machine Learning Model
    295
  7. My life cuts at Las Vegas during Thanksgiving day holiday
    7,376
  8. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    319
  9. Harness vs. OpenClaw: Two Very Different "Agents"
    912
  10. Clean Python Environments: The Power of venv vs. Docker
    784
  11. What is Docker? Why is Docker also useful in a development environment?
    591
  12. UIUC 2026-2027 Academic Calendar
    1,505
  13. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    771
  14. Open-Source LLMs: The AI Revolution
    726
  15. Resume 2.0: Leveling Up for My First Software Gig
    2,116
  16. Not everyone will understand what this man just did
    1,748
  17. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,554
  18. Unpacking IU's Shopper
    719
  19. Jackie Chan's Police Story: The Action Masterpiece
    616
  20. The IVE Story: Identity, 'I AM' Charts, and Influence
    916
  21. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,154
  22. Open Databases for Sex Crime Occurrences in the U.S.
    687
  23. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,546
  24. My First Day at University of Illinois-Urvana Champaign
    1,161
  25. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,094
  26. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,169
  27. Sipping the Stars: My Starbucks Adventure
    9,593
  28. Exciting explore at Sequoia National Park
    7,624
  29. My Life Shot at Death Valley
    1,648
  30. Ip Man fights with Muay Thai Master
    910
  31. Mad Clown - Don't Die
    982
  32. How to get Student Enrollment and Degree Verification at UIUC
    4,687
  33. LAX Thanksgiving Rush: A Joyful Reunion
    901
  34. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,087
  35. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    952
  36. 10CM - To Reach You (너에게 닿기를)
    1,133
  37. Feeling weak? Transform yourself at the UIUC ARC!
    1,551
  38. BOYNEXTDOOR - If I Say I Love You
    1,163
  39. The Future of Software Engineer - AI Engineering
    914
  40. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    886
  41. Lie - Legend song by BIGBANG
    7,790
  42. Why ROLLBACK is useful when you work with Google Gemini CLI?
    808
  43. Reimbursement after Vaccination at McKinley Health Center
    986
  44. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    941
  45. Common Questions from UIUC school life in terms of CS Program
    1,083
  46. UIUC Immunization Compliance
    1,176
  47. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,071
  48. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,072
  49. Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)
    847
  50. Common methods to improve coding skills
    969