Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Basics

Java Loops: for, while, do-while and for-each

A loop checks a condition, runs the body, updates, and goes round again. Five small programs: a for loop, a running sum to 15, a while loop that doubles Priya's savings, a do-while menu and a for-each over prices.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Name the three parts of a for loop: start, check and update
  • Keep a running total in a loop and avoid the off-by-one mistake
  • Choose between for, while, do-while and for-each for a job
  • Spot and fix an infinite loop

Before you start

  • Java if, else and switch

Say you want to greet Emma, Jack, Priya and Lucas. You could copy and paste the same line four times, but that falls apart quickly. A loop repeats an action for you, like a conveyor belt that keeps going round.

Check, run the body, update

A loop has three parts:

  • a start value: int i = 1
  • a check (the stopping rule): i <= 5
  • an update: i++

Each pass, the loop checks the condition, runs the body, then updates. It stops the first time the check is false.

A loop cycle: start i = 1, check i <= 5, body sum += i, update i++, back to the check. Sum goes 1, 3, 6, 10, 15. When i is 6 the check is false and the loop exits with sum 15. i = 1 i <= 5 ? sum += i i++ exit sum = 15 true false (i = 6) sum: 1, 3, 6, 10, 15
Check, body, update, and round again until the check is false.

A for loop

package org.studyeasy.s02l10;

public class Ex01_ForLoop {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("Hello, user " + i);
        }
    }
}
Hello, user 0
Hello, user 1
Hello, user 2
Hello, user 3
Hello, user 4

All three parts sit in the header. The body runs once per pass with i at 0, 1, 2, 3, 4. When i reaches 5 the check fails, which is why "user 5" never prints. Change the check to i <= 5 and the loop runs six times.

A loop that keeps a total

package org.studyeasy.s02l10;

public class Ex02_RunningSum {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
            System.out.println("i = " + i + ", sum = " + sum);
        }
        System.out.println("Total: " + sum);
    }
}
i = 1, sum = 1
i = 2, sum = 3
i = 3, sum = 6
i = 4, sum = 10
i = 5, sum = 15
Total: 15

sum lives outside the loop so every pass can add to it. <= includes the 5. The last println sits after the closing brace, so it prints once, when the loop is done.

Write i < 5 instead and the 5 is never added: the total drops to 10. That's the classic off-by-one mistake.

A while loop: until a goal is hit

package org.studyeasy.s02l10;

public class Ex03_WhileLoop {
    public static void main(String[] args) {
        double balance = 1000;
        int year = 0;
        while (balance < 2000) {
            balance = balance * 1.10;
            year++;
        }
        System.out.println("Priya reaches " + Math.round(balance) + " after " + year + " years");
    }
}
Priya reaches 2144 after 8 years

A while only has the check. The start values are set before the loop, and the update lives inside the body. Use it when you don't know the count up front: here, keep growing the balance by 10% a year until it passes 2000.

A do-while loop: at least once

package org.studyeasy.s02l10;

public class Ex04_DoWhile {
    public static void main(String[] args) {
        int count = 10;
        do {
            System.out.println("Menu shown, count = " + count);
            count++;
        } while (count < 5);
        System.out.println("Count is now " + count);
    }
}
Menu shown, count = 10
Count is now 11

The check comes last. 10 < 5 is false, yet the body already ran once. Turn it into a plain while (count < 5) and the menu line never appears. Use do-while when something must happen at least once, like showing a menu.

A for-each loop: one pass per item

package org.studyeasy.s02l10;

public class Ex05_ForEach {
    public static void main(String[] args) {
        int[] prices = {10, 20, 30};
        int total = 0;
        for (int p : prices) {
            total += p;
            System.out.println("p = " + p + ", total = " + total);
        }
        System.out.println("Total: " + total);
    }
}
p = 10, total = 10
p = 20, total = 30
p = 30, total = 60
Total: 60

prices is an array, a series of values in one variable (more in Java arrays). Read the header as "for each p in prices". p holds one price per pass, and there's no counter or stop condition to get wrong. Add a 40 to the array and the loop picks it up by itself: total 100.

Forget the update and the loop hangs

Take a while loop that prints users but has no i++ in its body:

// buggy on purpose: nothing changes i
int i = 0;
while (i < 5) {
    System.out.println("Hello, user " + i);
}

i stays 0, 0 < 5 is true every time, and the same line prints forever. That's an infinite loop; in IntelliJ, press the red stop square. The fix is the missing update. Something in the body must move the condition toward false.

Pick the loop that fits

LoopUse it when
foryou count passes with a counter
whileyou loop until something changes
do-whilethe body must run at least once
for-eachyou walk through every item in a series

for and while can do each other's jobs, so pick whichever reads better. Next, control a loop from the inside with break, continue and nested loops.

Keep going in Java · 12 of 79

Previous
Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
Next post
Java break, continue and Nested Loops
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program

Install JDK 25 (Microsoft Build of OpenJDK) with JAVA_HOME, install IntelliJ IDEA, then point a run configuration at the JDK and the main class and run Hello World.

Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA

Open IntelliJ's AI Chat, pick Claude Agent (the agent behind Claude Code) or Copilot and a model, ask in plain words for Main.java to print the date and time, review the change, and run it.

Java Hello World with Maven: What the JDK Does and What Maven Adds

javac compiles HelloWorld.java into bytecode and java runs it on the JVM. Maven adds one pom.xml, the same folders in every project and one build command. Then a real Maven Hello World in IntelliJ.

Java Variables, Keywords and Naming Rules

A variable is a labelled jar that holds one value at a time. Four small programs show declaring, reassigning, the names Java accepts, the keywords it reserves, and why daysUntilLaunch beats d.

On this page

  • Check, run the body, update
  • A for loop
  • A loop that keeps a total
  • A while loop: until a goal is hit
  • A do-while loop: at least once
  • A for-each loop: one pass per item
  • Forget the update and the loop hangs
  • Pick the loop that fits
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.