Working with for Loops in Java
Course: Core Java Training
Topic: Working with for Loops
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to for Loops in Java
A for loop is a control-flow statement in Java that repeatedly executes a block of code while a specified condition remains true. It is especially useful when the number of repetitions is known or when a task follows a predictable counting pattern.
For example, if a program needs to print numbers from 1 to 10, calculate the sum of several values, or process every element in an array, a for loop can perform the repeated work without writing the same statements many times.
Loops are an important part of Core Java because they help developers build efficient programs for calculations, data processing, validation, and automation.
Why Are for Loops Important?
- Repeat instructions without duplicating code.
- Perform calculations over a sequence of numbers.
- Access and process array elements.
- Generate tables, patterns, and reports.
- Reduce repetitive programming work.
- Control how many times a block of code executes.
2. Syntax of a for Loop
A standard Java for loop contains three main parts: initialization, condition, and update.
for (initialization; condition; update) {
// Statements to execute repeatedly
}
| Component |
Purpose |
Example |
| Initialization |
Creates or initializes a loop-control variable. |
int i = 1 |
| Condition |
Determines whether the loop should continue. |
i <= 5 |
| Update |
Changes the loop-control variable after each iteration. |
i++ |
| Loop body |
Contains the statements executed during each iteration. |
System.out.println(i); |
The initialization normally runs once at the beginning. Java checks the condition before each iteration. If the condition is true, the loop body runs and then the update executes. If the condition is false, the loop terminates.
3. How a for Loop Executes
Consider the following example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
Execution takes place in this order:
- Initialization: The variable
i is initialized to 1.
- Condition check: Java checks whether
i <= 5.
- Loop body: If the condition is true, the current value of
i is printed.
- Update: The statement
i++ increases the value of i by 1.
- Repeat: Java checks the condition again and continues while it remains true.
- Termination: When
i becomes 6, the condition is false and the loop ends.
4. Printing Numbers Using a for Loop
One of the simplest uses of a for loop is printing a sequence of numbers.
Example: Print Numbers from 1 to 10
public class PrintNumbers {
public static void main(String[] args) {
for (int number = 1; number <= 10; number++) {
System.out.println(number);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
The loop begins at 1, increases the variable by one after every iteration, and stops after printing 10.
Example: Print Numbers from 10 to 1
public class ReverseCounting {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.println(i);
}
}
}
Output:
10
9
8
7
6
5
4
3
2
1
Using i-- decreases the variable by one, allowing the loop to count backward.
5. Understanding Loop Initialization, Condition, and Update
Each component of a for loop has a specific responsibility. Understanding these parts helps prevent incorrect results and infinite loops.
Initialization
Initialization usually declares and assigns a loop variable before the first iteration.
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
The variable i starts at zero. When declared inside the loop header, its scope is generally limited to that loop.
Condition
The condition is evaluated before each iteration. If it evaluates to true, the loop body executes. If it evaluates to false, the loop ends.
for (int i = 1; i < 4; i++) {
System.out.println(i);
}
This loop prints 1, 2, and 3 because the condition becomes false when i reaches 4.
Update
The update changes the loop-control variable after the loop body completes normally.
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
Output:
2
4
6
8
10
The expression i += 2 increases the value of i by two on each iteration.
6. Using Increment and Decrement Operators in for Loops
Increment and decrement operators are commonly used in loop updates.
| Operator |
Meaning |
Example |
i++ |
Increases i by 1. |
for (int i = 0; i < 5; i++) |
i-- |
Decreases i by 1. |
for (int i = 5; i > 0; i--) |
i += 2 |
Increases i by 2. |
for (int i = 2; i <= 10; i += 2) |
i *= 2 |
Multiplies i by 2 after each iteration. |
for (int i = 1; i < 20; i *= 2) |
Example: Print Odd Numbers
public class OddNumbers {
public static void main(String[] args) {
for (int i = 1; i <= 15; i += 2) {
System.out.println(i);
}
}
}
Output:
1
3
5
7
9
11
13
15
7. Calculating the Sum of Numbers
A for loop can repeatedly add values to a variable. This technique is called accumulation.
Example: Sum of Numbers from 1 to 10
public class SumExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 55
The variable sum starts at zero. On every iteration, the current value of i is added to it. After the loop finishes, sum contains the total of all integers from 1 through 10.
Example: Sum of Even Numbers
public class EvenSum {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 20; i += 2) {
sum += i;
}
System.out.println("Sum of even numbers: " + sum);
}
}
Output:
Sum of even numbers: 110
8. Calculating a Factorial Using a for Loop
The factorial of a non-negative integer is the product of all positive integers up to that number. It is represented by an exclamation mark. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. By definition, 0! = 1.
Example: Factorial of 5
public class FactorialExample {
public static void main(String[] args) {
int number = 5;
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
System.out.println("Factorial: " + factorial);
}
}
Output:
Factorial: 120
The variable factorial starts at 1 because multiplying by zero would make the result zero. For larger inputs, choose a numeric type that can hold the result or use BigInteger to support arbitrarily large integer values.
9. Using for Loops with Arrays
Arrays store multiple values of the same declared element type. A traditional for loop can access array elements by using an index, starting at zero and ending at array.length - 1.
Example: Print Array Elements
public class ArrayLoopExample {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};
for (int i = 0; i < marks.length; i++) {
System.out.println(marks[i]);
}
}
}
Output:
85
90
78
92
88
The expression marks.length returns the number of elements in the array. Using it in the condition makes the loop adapt if the array size changes.
Example: Find the Largest Array Element
public class LargestElement {
public static void main(String[] args) {
int[] numbers = {12, 45, 7, 89, 32};
int largest = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i];
}
}
System.out.println("Largest: " + largest);
}
}
Output:
Largest: 89
This approach initializes the largest value using the first array element and compares the remaining elements one by one. It assumes the array is not empty.
10. Enhanced for Loop (for-each)
Java also provides an enhanced for loop, often called a for-each loop. It is designed to process each element of an array or an object that implements Iterable without explicitly managing an index.
Syntax
for (dataType element : collection) {
// Process the current element
}
Example
public class EnhancedForExample {
public static void main(String[] args) {
String[] names = {"Amit", "Priya", "Rahul"};
for (String name : names) {
System.out.println(name);
}
}
}
Output:
Amit
Priya
Rahul
| Traditional for Loop |
Enhanced for Loop |
| Provides access to an index. |
Directly provides each element. |
| Useful when the index is required. |
Useful when processing every element in order. |
| Can move forward, backward, or skip elements with a suitable update. |
Normally visits each element in iteration order. |
| Can update array elements through their indexes. |
Reassigning the loop variable does not replace the original array element. |
11. Nested for Loops
A nested for loop is a loop placed inside another loop. The inner loop runs for each iteration of the outer loop. Nested loops are useful for working with tables, matrices, grids, and patterns.
Example: Print a Rectangle of Stars
public class RectanglePattern {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 4; column++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
* * * *
* * * *
* * * *
The outer loop controls the rows, while the inner loop controls the number of stars printed in each row. The inner loop completes all four iterations before the outer loop moves to the next row.
Example: Multiplication Table
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}
This program prints multiplication tables from 1 to 5, with each table containing products from 1 through 10.
12. Using break in a for Loop
The break statement immediately terminates the nearest enclosing loop. It is useful when a result has been found or when continuing the loop is no longer necessary.
Example: Stop at Number 5
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
When i becomes 5, the break statement ends the loop before the print statement executes for that value.
13. Using continue in a for Loop
The continue statement skips the remaining statements in the current iteration and moves to the next iteration. In a traditional for loop, the update expression still runs after continue transfers control to the next iteration.
Example: Skip Even Numbers
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
Output:
1
3
5
7
9
The condition i % 2 == 0 identifies even numbers. When it is true, continue skips printing that number.
14. Omitting Parts of a for Loop
Java allows the initialization, condition, or update section of a for loop to be omitted. The semicolons that separate these sections must remain in place.
Example: Initialization Outside the Loop
public class OmittedInitialization {
public static void main(String[] args) {
int i = 1;
for (; i <= 3; i++) {
System.out.println(i);
}
}
}
Example: Update Inside the Loop Body
public class OmittedUpdate {
public static void main(String[] args) {
for (int i = 1; i <= 3;) {
System.out.println(i);
i++;
}
}
}
Both examples print numbers from 1 to 3. Although these forms are valid, keeping initialization, condition, and update in the loop header is usually easier to read when the loop follows a simple counting pattern.
15. Infinite for Loops
An infinite loop continues indefinitely because its condition never becomes false or is omitted. One common form is:
for (;;) {
System.out.println("Running...");
}
This loop has no initialization, condition, or update expression. Because the condition is omitted, it is treated as always true.
Infinite loops can be intentional in applications such as event-processing systems, but they should include a suitable exit mechanism when termination is required. An accidental infinite loop may consume CPU time and prevent the program from progressing.
Example: Common Infinite Loop Mistake
for (int i = 1; i <= 5; ) {
System.out.println(i);
// Missing update to i
}
In this example, i remains 1, so the condition stays true. Add an update such as i++ or use an appropriate loop structure to prevent unintended infinite execution.
16. Common Mistakes When Working with for Loops
| Mistake |
Problem |
Solution |
| Incorrect condition |
The loop may execute too many or too few times. |
Check the starting value and stopping boundary carefully. |
| Off-by-one error |
A loop may skip the final value or include an unwanted extra value. |
Choose between operators such as < and <= deliberately. |
| Missing update |
The loop may never terminate. |
Ensure the control variable changes so the condition can eventually become false. |
| Wrong update direction |
The condition may remain true indefinitely. |
Match increment or decrement direction to the condition. |
| Array index out of bounds |
Accessing an invalid index throws an exception. |
Use a condition such as i < array.length. |
| Incorrect accumulator initialization |
A sum or product may start from the wrong value. |
Usually initialize sums to 0 and products to 1. |
| Unintended semicolon |
A semicolon immediately after the loop header creates an empty loop body. |
Check loop punctuation and braces. |
| Modifying a loop variable unexpectedly |
Changing the counter in multiple places can make execution difficult to follow. |
Keep loop control simple and predictable. |
17. Best Practices for Using for Loops
- Use meaningful loop variable names when the purpose is not obvious.
- Keep the loop condition easy to understand.
- Choose a clear starting value and update expression.
- Use
array.length rather than hard-coded array boundaries.
- Prefer an enhanced
for loop when you need every element and do not need the index.
- Avoid unnecessary work inside a loop, especially when it can be calculated once outside it.
- Use
break and continue only when they make the control flow clearer.
- Avoid modifying the loop counter in multiple places unless there is a clear reason.
- Test boundary conditions, including zero iterations and the final iteration.
- Use nested loops carefully because their execution time can grow quickly as input sizes increase.
18. Practical Project: Student Marks Analyzer
In this mini-project, a for loop processes an array of student marks to calculate the total, average, and highest score.
public class StudentMarksAnalyzer {
public static void main(String[] args) {
int[] marks = {78, 85, 92, 67, 88};
int total = 0;
int highest = marks[0];
for (int i = 0; i < marks.length; i++) {
total += marks[i];
if (marks[i] > highest) {
highest = marks[i];
}
}
double average = (double) total / marks.length;
System.out.println("Total Marks: " + total);
System.out.println("Average Marks: " + average);
System.out.println("Highest Marks: " + highest);
}
}
Output:
Total Marks: 410
Average Marks: 82.0
Highest Marks: 92
Project Explanation
- The array stores five student marks.
- The loop visits each array element using its index.
- The
total variable accumulates all marks.
- The
highest variable stores the largest mark found so far.
- The average is calculated by dividing the total by the number of marks.
- The cast to
double ensures that the division can produce a decimal result.
19. Practice Exercises
- Write a program to print numbers from 1 to 100.
- Print all even numbers between 1 and 50.
- Print all odd numbers between 1 and 50.
- Calculate the sum of integers from 1 to a user-provided number.
- Calculate the factorial of a non-negative integer.
- Print the multiplication table of a number entered by the user.
- Use a loop to reverse-count from 20 to 1.
- Find the largest and smallest values in an integer array.
- Count how many positive, negative, and zero values exist in an array.
- Use nested loops to print a right-angled triangle of stars.
- Use
continue to skip numbers divisible by 3.
- Use
break to stop searching an array when a target value is found.
20. Interview Questions and Answers
Q1. What is a for loop in Java?
A for loop is an iteration statement that repeatedly executes a block of code while its condition evaluates to true.
Q2. What are the three main parts of a for loop?
Initialization, condition, and update. Initialization normally runs once, the condition is checked before each iteration, and the update runs after an iteration completes normally.
Q3. What is the difference between a for loop and a while loop?
A for loop places initialization, condition, and update together in its header. A while loop places its condition in the header, while initialization and updating are usually written separately. Both can implement repetition.
Q4. What is a nested for loop?
A nested for loop is a loop inside another loop. It is commonly used for matrices, grids, tables, and patterns.
Q5. What does the break statement do?
The break statement immediately terminates the nearest enclosing loop or switch statement.
Q6. What does the continue statement do?
The continue statement skips the remaining statements in the current loop iteration and proceeds to the next iteration.
Q7. Can a for loop run without initialization?
Yes. Initialization can be omitted from the header if the loop variable is initialized elsewhere, but the separating semicolons must remain.
Q8. What is an infinite for loop?
An infinite for loop is one that continues indefinitely because its condition never becomes false or is omitted. The form for (;;) is a common example.
Q9. What is the difference between a traditional for loop and an enhanced for loop?
A traditional loop provides explicit control over an index and update. An enhanced loop directly visits elements in an array or an Iterable collection, making it convenient when an index is unnecessary.
Q10. Why is array.length used in a loop condition?
It provides the array's element count, allowing the loop to process valid indexes from zero through array.length - 1 without hard-coding the size.
Q11. What is an off-by-one error?
An off-by-one error occurs when a loop boundary causes one extra or one fewer iteration than intended. Carefully selecting < or <= helps avoid this problem.
Q12. Can a for loop contain multiple initialization or update expressions?
Yes. Java permits comma-separated expressions in the initialization and update sections, provided they follow Java's syntax rules. For example, for (int i = 0, j = 10; i < j; i++, j--) updates two variables together.
21. Quick Revision Checklist
- Understand the syntax and execution order of a
for loop.
- Know how initialization, condition, and update work.
- Practise counting forward and backward.
- Use loops for sums, factorials, and multiplication tables.
- Process arrays safely using valid indexes.
- Understand enhanced loops and nested loops.
- Use
break to terminate a loop and continue to skip an iteration.
- Recognize infinite loops and off-by-one errors.
- Apply loops to practical data-processing tasks.
22. Conclusion
The for loop is a fundamental Java programming construct used to repeat instructions efficiently. By understanding initialization, conditions, updates, array traversal, nested loops, and control statements such as break and continue, you can solve a wide range of programming problems. Regular practice with counting programs, calculations, patterns, and arrays will strengthen your Core Java skills.
Explore more programming concepts through the Core Java Training course, register through the JustAcademy course demo page, or visit the JustAcademy homepage.