Mastering For Loops in Java: A Comprehensive Guide

Mastering For Loops in Java: A Comprehensive Guide

4 mins read393 Views Comment
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 11, 2023 21:02 IST

Learn how to use for loops in Java to control the flow of your programs and automate repetitive tasks. Understand the basics of for loops, nested for loops, for-each loops and more.

2022_02_j.jpg

A for loop in Java is a looping technique that helps a computer repeat a task multiple times. Like counting numbers from 1 to 10 or printing names from an array list. It’s like giving the computer instructions and making it do the same thing again and again. It helps automate tasks and make them faster.

In Java, we use for loop to iterate over a sequence of elements, such as an array or a list.

Syntax of a for loop in Java

The syntax of a for loop in Java includes an initialization statement, a termination condition, and an increment or update statement. The basic structure of a for loop is:

for (initialization; condition; increment/decrement) {
    // code to be executed
}
  • “initialization” sets up the loop and starts the counting
  • “condition” is a question that determines if the loop continues
  • “increment/decrement” is how the computer moves to the next step in the loop.

For example, the following code uses a for loop to iterate over an array of integers and print out each element:

 
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Copy code

This code initializes a loop counter variable i to 0, checks that i is less than the length of the numbers array (the termination condition), and at the end of each iteration increments i by 1.

Nested for loop in Java

  • A nested for loop is a for loop inside another for loop
  • It lets the computer do multiple sets of instructions, one inside the other
  • Inner loop will execute full iteration for each iteration of the outer loop.
  • Useful for tasks such as processing multi-dimensional arrays and complex operations on multiple lists of data.

The basic syntax for a nested for loop in Java is:

for (initialization1; termination1; increment1) {
    // code to be executed in the outer loop

    for (initialization2; termination2; increment2) {
        // code to be executed in the inner loop
    }
}

Here is an example of a nested for loop in Java:

 
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("I'm watching movie " + (j + 1) + " in theater " + (i + 1));
}
}
Copy code

How is Nested Loop working in the above code?

  • The first for loop iterates over the three theaters with variable “i”
  • The second for loop is inside the first one, iterates over two movies in each theater with variable “j”
  • It prints out which movie the person is watching in which theater using the values of “i” and “j”

Output:

I'm watching movie 1 in theater 1
I'm watching movie 2 in theater 1
I'm watching movie 1 in theater 2
I'm watching movie 2 in theater 2
I'm watching movie 1 in theater 3
I'm watching movie 2 in theater 3

Printing Multiplication Table using Nested For Loop in Java

 
public class MultiplicationTable {
public static void main(String[] args) {
int rows = 10; // Number of rows in the table
int columns = 10; // Number of columns in the table
// Outer loop iterates through the rows
for (int i = 1; i <= rows; i++) {
// Inner loop iterates through the columns
for (int j = 1; j <= columns; j++) {
System.out.print(i * j + " "); // Multiply and print the current row and column
}
System.out.println(); // Move to the next row
}
}
}
Copy code

Note: Using nested loops increases the number of operations the program has to perform, which can make the program slower, especially when dealing with large data sets or complex operations. It’s important to consider the performance when using nested loops and make sure that they are necessary to achieve the desired outcome.

Read More:

Swapping of Two Numbers in Java
Swapping of Two Numbers in Java
Get an introduction to swapping the values of two numbers in Java using different methods. Compare the use of a temporary variable, arithmetic operators, and bitwise operators for swapping numbers....read more
How to Check Leap Year in Java?
How to Check Leap Year in Java?
In this blog, you will learn how to check leap year in Java. A leap year is a year that is divisible by 4 and 400 but not by 100....read more
Switch Case in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
350 hours
Free
6 months
– / –
4 months
– / –
– / –
– / –
1 month
40 K
7 weeks
7.8 K
3 months
8.47 K
2 months
7 K
6 months
4 K
2 months

Using for loop in Java for Arrays and Collection

We can use traditional for loop to loop through the elements of an array by using the index. Just like we did earlier in this blog.

 
String[] words = {"Hello", "world", "!"};
for (int i = 0; i < words.length; i++) {
String word = words[i];
System.out.println(word);
}
Copy code

You can use enhanced version of for loop to iterate through a collection. We call it for-each loop in Java . Here is an example:

Syntax of for loop for Arrays and Collection

for(datatype var : array/collection){
  // do something
}

This is called enhanced for loop (for each loop) and is used to iterate through an array and Collection.

 
String[] words = {"Hello", "world", "!"};
for (String word : words) {
System.out.println(word);
}
Copy code

This loop will iterate over all elements in the words array and print out each one.

Read More: Mastering For each loop in Java

NOTE: If a for loop is too complex or contains too many nested loops, it can make the code harder to read and understand. This can cause maintenance issues and make it difficult for other developers to understand the code.

Summary

  • for loops in Java are used to repeat a block of code a certain number of times.
  • The basic structure of a for loop includes an initialization, termination condition, and an increment or update statement.
    • Initialization statement is executed once before the loop starts
    • Termination condition is checked before each iteration
    • Increment statement is executed after each iteration.
  • for loops can be used to iterate over arrays and collections.
  • enhanced for loop allows you to iterate through an array or collection in a concise and easy to read way.
  • for loops are useful when you want to perform the same action on a large number of elements, or when you need to execute a block of code a specific number of times.

In conclusion, we use for loops in Java to perform a wide range of tasks, from iterating over arrays and collections to automating repetitive tasks. Understanding how to use for loops can greatly improve the efficiency of your code, and make it easier to read and understand.
To dive deeper into the topic, you can explore more examples and best practices of using for loops along with other looping techniques in Java like while loop and do-while loop.
You can check out more articles and tutorials related to for loops in Java by subscribing to our website. If you find this article helpful, please don’t hesitate to share it with others and give a like as well.

Read More:

Armstrong Number in Java using Different Methods
Armstrong Number in Java using Different Methods
Learn to check if a number is an Armstrong number in Java using while loop or recursion. Understand the mathematical definition and see code examples for easy implementation
Check Palindrome in Java Using Different Methods
Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation,...read more
Fibonacci Series in Java [Case-Study Based]
Fibonacci Series in Java [Case-Study Based]
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, the Fibonacci...read more
About the Author
author-image
Atul Harsha
Senior Manager Content

Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio