
- Java - Home
- Java - Overview
- Java - History
- Java - Features
- Java Vs. C++
- JVM - Java Virtual Machine
- Java - JDK vs JRE vs JVM
- Java - Environment Setup
- Java - Hello World Program
- Java - Comments
- Java - Basic Syntax
- Java - Variables
- Java - Data Types
- Java - Type Casting
- Java - Unicode System
- Java - User Input
- Java - Date & Time
Java Operators
- Java - Operators
- Java - Arithmetic Operators
- Java - Assignment Operators
- Java - Relational Operators
- Java - Logical Operators
- Java - Bitwise Operators
- Java Operator Precedence & Associativity
Java Control Statements
- Java - Decision Making
- Java - If Else Statement
- Java - Switch Statement
- Java - Loop Control
- Java - For Loop
- Java - For-Each Loop
- Java - While Loop
- Java - Do While Loop
- Java - Break Statement
- Java - Continue Statement
Object Oriented Programming
- Java - OOPs Concepts
- Java - Object & Classes
- Java - Class Attributes
- Java - Class Methods
- Java - Methods
- Java - Variables Scope
- Java - Constructors
- Java - Access Modifiers
- Java - Inheritance
- Java - Aggregation
- Java - Polymorphism
- Java - Overriding
- Java - Method Overloading
- Java - Dynamic Binding
- Java - Static Binding
- Java - Instance Initializer Block
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java - Inner Classes
- Java - Static Class
- Java - Anonymous Class
- Java - Singleton Class
- Java - Wrapper Classes
- Java - Enums
- Java - Enum Constructor
- Java - Enum Strings
Java Built-in Classes
Java File Handling
- Java - Files
- Java - Create a File
- Java - Write to File
- Java - Read Files
- Java - Delete Files
- Java - Directories
- Java - I/O Streams
Java Error & Exceptions
- Java - Exceptions
- Java - try-catch Block
- Java - try-with-resources
- Java - Multi-catch Block
- Java - Nested try Block
- Java - Finally Block
- Java - throw Exception
- Java - Exception Propagation
- Java - Built-in Exceptions
- Java - Custom Exception
Java Multithreading
- Java - Multithreading
- Java - Thread Life Cycle
- Java - Creating a Thread
- Java - Starting a Thread
- Java - Joining Threads
- Java - Naming Thread
- Java - Thread Scheduler
- Java - Thread Pools
- Java - Main Thread
- Java - Thread Priority
- Java - Daemon Threads
- Java - Thread Group
- Java - Shutdown Hook
Java Synchronization
- Java - Synchronization
- Java - Block Synchronization
- Java - Static Synchronization
- Java - Inter-thread Communication
- Java - Thread Deadlock
- Java - Interrupting a Thread
- Java - Thread Control
- Java - Reentrant Monitor
Java Networking
- Java - Networking
- Java - Socket Programming
- Java - URL Processing
- Java - URL Class
- Java - URLConnection Class
- Java - HttpURLConnection Class
- Java - Socket Class
- Java - Generics
Java Collections
Java Interfaces
- Java - List Interface
- Java - Queue Interface
- Java - Map Interface
- Java - SortedMap Interface
- Java - Set Interface
- Java - SortedSet Interface
Java Data Structures
Java Collections Algorithms
Advanced Java
- Java - Command-Line Arguments
- Java - Lambda Expressions
- Java - Sending Email
- Java - Applet Basics
- Java - Javadoc Comments
- Java - Autoboxing and Unboxing
- Java - File Mismatch Method
- Java - REPL (JShell)
- Java - Multi-Release Jar Files
- Java - Private Interface Methods
- Java - Inner Class Diamond Operator
- Java - Multiresolution Image API
- Java - Collection Factory Methods
- Java - Module System
- Java - Nashorn JavaScript
- Java - Optional Class
- Java - Method References
- Java - Functional Interfaces
- Java - Default Methods
- Java - Base64 Encode Decode
- Java - Switch Expressions
- Java - Teeing Collectors
- Java - Microbenchmark
- Java - Text Blocks
- Java - Dynamic CDS archive
- Java - Z Garbage Collector (ZGC)
- Java - Null Pointer Exception
- Java - Packaging Tools
- Java - Sealed Classes
- Java - Record Classes
- Java - Hidden Classes
- Java - Pattern Matching
- Java - Compact Number Formatting
- Java - Garbage Collection
- Java - JIT Compiler
Java Miscellaneous
- Java - Recursion
- Java - Regular Expressions
- Java - Serialization
- Java - Strings
- Java - Process API Improvements
- Java - Stream API Improvements
- Java - Enhanced @Deprecated Annotation
- Java - CompletableFuture API Improvements
- Java - Streams
- Java - Datetime Api
- Java 8 - New Features
- Java 9 - New Features
- Java 10 - New Features
- Java 11 - New Features
- Java 12 - New Features
- Java 13 - New Features
- Java 14 - New Features
- Java 15 - New Features
- Java 16 - New Features
Java APIs & Frameworks
Java Class References
- Java - Scanner
- Java - Arrays
- Java - Strings
- Java - Date
- Java - ArrayList
- Java - Vector
- Java - Stack
- Java - PriorityQueue
- Java - LinkedList
- Java - ArrayDeque
- Java - HashMap
- Java - LinkedHashMap
- Java - WeakHashMap
- Java - EnumMap
- Java - TreeMap
- Java - IdentityHashMap
- Java - HashSet
- Java - EnumSet
- Java - LinkedHashSet
- Java - TreeSet
- Java - BitSet
- Java - Dictionary
- Java - Hashtable
- Java - Properties
- Java - Collection
- Java - Array
Java Useful Resources
Java - for Loop
In Java, a for loop is a repetition control structure used to execute a block of code a specific number of times. It is particularly useful when the number of iterations is known beforehand, making it an efficient way to automate repetitive tasks.
For loops are used in Java for tasks such as iterating over arrays, performing calculations, and handling repetitive operations.
Java for Loop
The Java for loop is an entry control loop, meaning it checks the given condition before executing the loop body. Its structured syntax makes it more readable and concise compared to other loop structures like the while loop.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) { // Statements }
Example
The following example demonstrates a simple for
loop that prints numbers from 1 to 5:
public class Test { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("Number: " + i); } } }
When the above code is compiled and executed, it produces the following result −
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
Structure of for Loop
The Java for
loop consists of four essential components:
1. Initialization
Defines and initializes the loop counter variable. This part executes only once at the start.
// Initialization example int i = 1; // Loop variable declared and initialized
2. Boolean Expression (Condition)
Evaluates before each iteration. If the condition evaluates to true
, the loop executes; if false
, it terminates.
// Condition example i <= 5; // Loop continues while i is less than or equal to 5
3. Body
Contains the statements that execute repeatedly as long as the Boolean condition remains true
. This section may also include an update to the loop counter.
// Body of the loop System.out.println("Iteration: " + i); // Executes in each iteration
4. Update
Modifies the loop counter at the end of each iteration.
// Update example i++; // Increments i by 1 after each iteration
The following is the complete syntax of a for loop with all four components:
for(int i = 1; i <= 5; i++) { System.out.println("Iteration: " + i); }
Execution Process of a for Loop
Here is the flow of control in a for loop −
The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables and this step ends with a semi colon (;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop will not be executed and control jumps to the next statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Flow Diagram
The following diagram shows the flow diagram (execution process) of a for loop in Java -

Examples of for Loop
Below are various examples demonstrating the usage of the for
loop in Java:
Example 1: Printing Numbers in a Range Using for Loop
In this example, we're showing the use of a for loop to print numbers starting from 10 to 19. Here we've initialized an int variable x with a value of 10 within initialization blook of for loop. Then in expression block, we're checking x as less than 20, and in the end under update block, we're incrementing x by 1. Within body of for loop, we're printing the value of x. For loop will run until x becomes 20. Once x is 20, loop will stop execution and program exits.
public class Test { public static void main(String args[]) { for(int x = 10; x < 20; x = x + 1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }
When the above code is compiled and executed, it produces the following result −
value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19
Example 2: Printing Array Elements Using for Loop
In this example, we're showing the use of a for loop to print contents of an array. Here we're creating an array of integers as numbers and initialized it some values. We've created a variable named index to represent index of the array within for loop, check it against size of the array and incremented it by 1. Within for loop body, we're printing element of the array using index notation. Once index becomes same as array size, for loop exits and program quits.
public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int index = 0; index < numbers.length; index++) { System.out.print("value of item : " + numbers[index] ); System.out.print("\n"); } } }
When the above code is compiled and executed, it produces the following result −
value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50
Nested for Loops
A nested for loop is a for loop containing another for loop inside it.
Example
In this example, we are printing tables of the numbers from 1 to 10.
public class Main { public static void main(String[] args) { // Implementing nested for loop // Initializing loop counters int num = 1; int i = 1; // outer for loop for (num = 1; num <= 10; num++) { //inner for loop System.out.print("Table of " + num + " is : "); for (i = 1; i <= 10; i++) { // printing table System.out.print(num * i + " "); } // printing a new line System.out.println(); } } }
When the above code is compiled and executed, it produces the following result −
Table of 1 is : 1 2 3 4 5 6 7 8 9 10 Table of 2 is : 2 4 6 8 10 12 14 16 18 20 Table of 3 is : 3 6 9 12 15 18 21 24 27 30 Table of 4 is : 4 8 12 16 20 24 28 32 36 40 Table of 5 is : 5 10 15 20 25 30 35 40 45 50 Table of 6 is : 6 12 18 24 30 36 42 48 54 60 Table of 7 is : 7 14 21 28 35 42 49 56 63 70 Table of 8 is : 8 16 24 32 40 48 56 64 72 80 Table of 9 is : 9 18 27 36 45 54 63 72 81 90 Table of 10 is : 10 20 30 40 50 60 70 80 90 100
Infinite for Loop
An infinite loop never ends unless you stop manually by pressing CTRL + C. To implement an infinite for loop either use such a condition that is always true or directly use true as the condition.
Example
In this example, we're showing the infinite loop using for loop. It will keep printing the numbers until you press ctrl+c to terminate the program.
public class Test { public static void main(String args[]) { int x = 10; for( ;; ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }
When the above code is compiled and executed, it produces the following result −
value of item : 10 value of item : 11 value of item : 12 value of item : 13 value of item : 14 ... ctrl+c
Use Cases of Java for Loop
The for
loop in Java is widely used for repetitive tasks. Below are some common use cases along with complete examples:
1. Iterating Over a Fixed Range of Numbers
When the number of iterations is known, a for
loop efficiently executes the required steps.
public class ForLoopExample { public static void main(String[] args) { for(int i = 1; i <= 10; i++) { System.out.println("Number: " + i); } } }
2. Traversing Arrays and Collections
The for
loop is commonly used to iterate through arrays or lists.
public class ArrayTraversal { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for(int i = 0; i < numbers.length; i++) { System.out.println("Element: " + numbers[i]); } } }
3. Implementing Nested Loops
It is useful for iterating over multi-dimensional structures such as matrices.
public class NestedLoopExample { public static void main(String[] args) { for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) { System.out.print(i + "," + j + " "); } System.out.println(); } } }
4. Repeating Tasks a Specific Number of Times
When a task needs to be repeated a set number of times, a for
loop is ideal.
public class RepeatTaskExample { public static void main(String[] args) { for(int i = 0; i < 5; i++) { System.out.println("Task executed: " + (i+1)); } } }
5. Using Enhanced for Loop (for-each)
Java provides an enhanced for
loop for iterating over arrays and collections.
public class EnhancedForLoopExample { public static void main(String[] args) { String[] fruits = {"Apple", "Banana", "Cherry"}; for(String fruit : fruits) { System.out.println(fruit); } } }