In Java For Loop is used to repeat a particular block of code a definite number of times. Despite the while loop which is used until a condition evaluates to true the for loop is used to repeat a group of statements for a definite range. In this article, let us understand the workings of Java For Loop clearly.
What is Looping in Java? ➿
Looping is a process where we can repeat a block of code or group of statements until a certain condition is met. Looping is a synonym for repeating where certain statements or blocks of a program are executed over and over again.
There are different types of loops in Java such as while loop, do while loop, and Java for loop. Each of these loops has its own advantages and limitations based on the requirements.
What is For Loop in Java?
Java For Loop can be used when you exactly know the number of times you want to loop a particular block of code. Instead of a while loop, you can use a for loop to repeat the execution of a particular group of statements a definite number of times.
Java For Loop Syntax⚙️✂️✂
Let us overview the syntax of Java For loop which starts with initialization, and condition and ends on update.
for(initial; condition; update) {
// Code to be executed in each iteration } |
Where,
Initial: It defines the starting point of the for loop
Condition: it specifies the condition up to which the loop is supposed to run
Update: This is an increment or decrement operator based on the condition which updates after each iteration.
Example for Java for Loop 🚀
Let us understand Java for Loop with the help of a simple example below.
Filename: ArrayTraversal.java
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 at index ” + i + “: ” + numbers[i]); } } } |
In the above code, the for loop iterates through each element in an array which is of size 5. The numbers. length calculates the size of the array and the loop starts iteration from 0 index to the size of the array.
The increment operator (++) is used to move to the next step in the iteration. Each iteration is printed on the screen until the conditions are met and the for loop is stopped.
Java For Each Loop Syntax And Example 🚀
Java for each loop is an extension type of Java for Loop which can iterate through arrays and collections easily and more conveniently. Let us understand For Each Loop working with the help of an example below.
Filename: ForEachListExample.java
import java.util.ArrayList;
public class ForEachListExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add(“Apple”); fruits.add(“Banana”); fruits.add(“Cherry”); for (String fruit: fruits) { System.out.println(fruit); } } } |
In this, for each loop, you need not mention three statements to run the loop. You will only need to write the name of the array and the “ for each” loop will run through each element in the array.
Nested Java For Loop Example
The Nested Java For loop consists of multiple layers of loops running over one another. The outer loop and inner loop are the main components of the Java For loop. Let us learn how to use nested Java loop and its importance in Java programming.
Nested Java For Loop Syntax
for (initial; condition; update) {
for (initial; condition; update) { // Code to execute inside the inner loop } } |
Nested Java For Loop Example
Suppose we have to run two Java for loops and print the result on the screen. Let us write the code for the nested Java loop below.
Filename: NestedForLoop.java
public class NestedForLoop {
public static void main(String[] args) { for (int i = 1; i <= 3; i++) { // Outer loop for (int j = 1; j <= 3; j++) { // Inner loop System.out.print(i + “,” + j + ” “); } System.out.println(); // Moves to the next line } } } |
Java For Loop with Break and Continuous Statement
Let us know how we can use the “break” and “continuous” statements in the Java For loop code below.
Break Statement
FileName: BreakExample.java
public class BreakExample {
public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { // Breaks the loop when i is 5 System.out.println(“Loop terminated at i = ” + i); break; } System.out.println(“i = ” + i); } System.out.println(“Outside the loop”); } } |
Continuous Statement
FileName: ContinueExample.java
public class ContinueExample {
public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { // Skips the iteration when i is 5 System.out.println(“Skipping i = ” + i); continue; } System.out.println(“i = ” + i); } } } |
Benefits of Using For Loop In Java w
There are many advantages to using For loops in Java; let us understand the complete benefits below.
Efficient Looping
The four loop is best suited when the number of iterations is known beforehand. The for loop makes the execution faster and more efficient.
Readable Syntax
Java For loop offers readable syntax, which improves readability and maintainability. The for loop provides a concise structure combining initial, condition, and update conditions.
Better Increment Options
The for loop provides you with increment, decrement, and other modification options with support of complex looping conditions and multiple loop variables.
Better Execution Controls
With Java For loops, you can use break and continuous statements to control the execution of loops effectively. It also helps in optimising the performance of a code and avoiding unnecessary iterations.
Effective for Arrays and Collections
You can easily iterate over arrays and collections using for each loop without any need for index management throughout the iteration. It also reduces the chances of any errors in the code based on the boundary conditions.
Supports Nested Loops
The Java For loop supports nested loop conditions where multi dimensional arrays, tables, and complex patterns can easily be interpreted using algorithms such as matrix multiplication and pattern printing.
Practice Exercises for Java For Loop
Check some of the practice questions based on Java Foor Loop. You can use online compilers or text editors to write and edit your code.
- Write a Java program to print numbers from 1 to 10 using a for loop.
- Print all even numbers from 1 to 50 using a for loop.
- Write a program to print the sum of the first 10 natural numbers using a for loop.
- Print all numbers from 100 to 1 in reverse order using a for loop.
- Write a program to calculate the factorial of a given number using a for loop.
- Write a Java program to find the maximum element in an array using a for loop.
- Write a program to calculate the sum of all elements in an array using a for loop.
- Print all elements of an array using an enhanced for loop (for-each loop).
- Count the number of even and odd numbers in an array using a for loop.
- Write a program to reverse an array using a for loop.
- Print a pattern of stars (*) using nested for loops:
*
* * * * * * * * * |
- Write a Java program to print the multiplication table of a given number using a nested for loop.
- Print a square pattern of numbers using nested for loops.
- Print a right-aligned triangle of numbers using a nested for loop.
- Write a program to generate a pyramid pattern using nested for loops.
- Write a program to print numbers from 1 to 20 but stop when the number is 13 using a break.
- Find the sum of the digits of a given number using a for loop.
- Print Fibonacci series up to 10 terms using a for loop.
- Write a program to count the number of digits in a given number using a for loop.
Learn Java Programming with PW Skills
Become proficient in Java programming language and build scalable Java applications with the Decode Java DSA Course. Learn about the latest Java trends and tools to master application development.
Get complete tutorials for Java fundamentals, API integration, and more. Get tutored by experienced mentors and build real-world projects with Java. Learn data structures in this self paced program only on pwskills.com
Java For Loop FAQs
Q1. What is For Loop in Java?
Ans: A Java For loop in Java is a control flow statement used to execute a block of code multiple times with a defined number of iterations. It consists of three parts: initialization, condition, and increment/decrement.
Q2. How many types of Java For Loop are there?
Ans: A simple for loop, for each loop, labeled for loop, and nested for loops are some of the loops in Java.
Q3. How is each loop different from the other for loops in Java?
Ans: A For each loop is used to iterate over arrays or collections without using an index variable.
Q4. Can a for loop be infinite?
Ans: Yes, a Java for loop can be infinitive when the conditions in the Java loop always evaluate to true.
Q5. How can we use nested for loops in Java?
Ans: A nested for loop is a for loop inside another for loop, useful for working with multi-dimensional arrays or patterns.