For Loop in Java | Important points
Last Updated :
17 Dec, 2021
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. In Java, just unlikely any programming language provides four ways for executing the loops namely while loop, for loop, for-each loop, do-while loop or we can call it basically three types of loops in some books as for-each loop is treated as enhanced for loop. Let us discuss for loop in details.
Generally, we tend to use while loops as we do get a better understanding if we are into learning loops but after a saturation, we as programmers tend to tilt towards for loop as it is cleaner and foundations are carried out in a straight go for which we have to carefully grasp syntax as follows:
Syntax: It consists of three parts namely as listed:
- Initialization of variables
- Specific condition as per requirement over which these defined variables are needed to be iterated
- A terminating part where we generally play with variables to reach to terminating condition state.
for(initialization; boolean expression; update statement) {
// Body of for loop
}
This is generally the basic pilgrimage structure of for loop.
Let’s look at some basic examples of using for loop and the common pitfalls in using for loop which enables us to know even better as internal working will be depicted as we will be playing with codes.
Usecase 1: Providing expression in for loop is a must
For loop must consist of a valid expression in the loop statement failing which can lead to an infinite loop. The statement
for ( ; ; )
is similar to
while(true)
Note: This above said is crux of advanced programming as it is origin of logic building in programming.
Example
Java
// Java program to illustrate Infinite For loop
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// For loop
for (;;) {
// Print statement everytime condition holds
// true making body to execute
System.out.println("This is an infinite loop");
}
}
}
Output: Prints the statement “This is an infinite loop” repeatedly.
This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
...
...
This is an infinite loop
Usecase 2: Initializing Multiple Variables
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
Example:
Java
// Java Program to Illustrate Initializing Multiple
// Variables in Initialization Block
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring an integer variable
int x = 2;
// For loop to iterate
for (long y = 0, z = 4; x < 10 && y < 10;
x++, y++) {
// Printing value/s stored in variable named y
// defined inside body of for loop
System.out.println(y + " ");
}
// Printing value/s stored in variable named x
// defined outside body of for loop
System.out.println(x);
}
}
In the above code, there is simple variation in the for loop. Two variables are declared and initialized in the initialization block. The variable ‘z’ is not being used. Also, the other two components contain extra variables. So, it can be seen that the blocks may include extra variables which may not be referenced by each other.
Usecase 3: Redeclaration of a Variable in the Initialization Block
Suppose, an initialization variable is already declared as an integer. Here we can not re-declare it in for loop with another data type as follows:
Example 1:
Java
// Java Program to Illustrate Redeclaring a Variable
// in Initialization Block
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring an integer variable
int x = 0;
// Redeclaring above variable
// as long will not work
for (long y = 0, x = 1; x < 5; x++) {
// Printing the value inside the variable
System.out.print(x + " ");
}
}
}
Output:
Example3.java:12: error: variable x is already defined in method main(String[])
for(long y = 0, x = 1; x < 5; x++)
Here, x was already initialized to zero as an integer and is being re-declared in the loop with data type long. But this problem can be fixed by slightly modifying the code. Here, the variables x and y are declared in a different way.
Example 2:
Java
// Java Program to Illustrate Redeclaring a Variable
// in Initialization Block
// Main class
public class GFG {
// main driver method
public static void main(String[] args)
{
// Declaring and initializing variables
int x = 0;
long y = 10;
// For loop to iterate over till
// custom specified check
for (y = 0, x = 1; x < 5; x++) {
// Printing value contained in memory block
// of the variable
System.out.print(x + " ");
}
}
}
Output:
1 2 3 4
Usecase 4: Variables declared in the initialization block must be of the same type
It is just common sense that when we declare a variable as shown below:
int x, y;
Here both variables are of the same type. It is just the same in for loop initialization block too.
Example:
Java
// Java program to Illustrate Declaring a Variable
// in Initialization Block
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Declaring integer variable
// int x;
// Note: This will cause error;
// Redeclaring x as long will not work
for (long y = 0, x = 1; x < 5; x++) {
// Printing the value stored
System.out.print(x + " ");
}
}
}
Usecase 5: Variables in the loop are accessible only within
The variables that are declared in the initialization block can be accessed only within the loop as we have as per the concept of the scope of variables.
Example:
Java
// Java Program to Illustrate Scope of Initializing
// Variables Within the oop
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// x and y scope is declared only
// within for loop
for (int x = 0, y = 0; x < 3 && y < 3; x++, y++) {
// Printing value stored in variable named y
System.out.println(y + " ");
}
// Printing value stored in variable named x
// after inner loop is over
System.out.println(x);
}
}
Error:
Example5.java:13: error: cannot find symbol
System.out.println(x);
In the above example, variable x is not accessible outside the loop. The statement which is commented gives a compiler error.
Similar Reads
Important Keywords in Java
Keywords refer to the reserved set of words of a language. These are used for some predefined actions. abstract: It is a non-access modifier applicable for classes and methods. It is used to achieve abstraction. For more, refer to abstract keyword in javaenum: It is used to define enum in Javainstan
2 min read
Important Points to Know About Java and Swift
Java is a general-purpose, class-based, object-oriented programming language and computing platform which was first developed by Sun Micro System in the year 1995. It was developed by James Gosling. It was designed to build web and desktop applications and have lesser implementation dependencies. It
3 min read
For-Each Loop in Java
The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example: Using a for-each lo
8 min read
Fast Output in Java
While doing problems in various coding platforms in some questions we end up with (TLE). At that point of time even if we use fast input then also, sometimes (TLE) remains in Java. At that time if we use fast output with fast input it can reduce the time taken. The fast output is generally used when
3 min read
Java for loop vs Enhanced for loop
In Java, loops are fundamental constructs for iterating over data structures or repeating blocks of code. Two commonly used loops are the for loop and the enhanced for loop. While they serve similar purposes, their applications and usage vary based on the scenario.for loop vs Enhanced for loopBelow
4 min read
Java For Loop
Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.Now let's go through a simple Java for lo
4 min read
Final Local Variables in Java
In Java, a local variable is a variable, which is declared inside a method. Local variables are only accessible within the method in which they are declared, other methods in the class do not know anything about that variable. When we declare a local variable, we need to initialize it first before u
3 min read
5 Most Common Java Pitfalls
1. Not understanding that String is an immutable class: The Java String class is immutable (Unmodifiable). This is because String objects are cached in a String pool. The object that a String is referencing to can change, but the String objects themselves cannot. Example: Java public class Main { pu
5 min read
dot(.) Operator in Java
The dot (.) operator is one of the most frequently used operators in Java. It is essential for accessing members of classes and objects, such as methods, fields, and inner classes. This article provides an in-depth look at the dot operator, its uses, and its importance in Java programming.Dot(.) Ope
4 min read
Compare two Strings in Java
String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
4 min read