w1coding.comAll tutorials

Java Loops

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Loops (for, while, do-while)

Java provides different types of loops to perform repetitive tasks.

For Loop

public class ForLoopExample {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Iteration: " + i);
        }
    }
}
    

This program uses a for loop to print the iteration number from 1 to 5.

While Loop

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println("Iteration: " + i);
            i++;
        }
    }
}
    

This example demonstrates the use of a while loop to perform the same task as the for loop above.

Do-While Loop

public class DoWhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        do {
            System.out.println("Iteration: " + i);
            i++;
        } while (i <= 5);
    }
}
    

The do-while loop guarantees at least one iteration even if the condition is false at the start.