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
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
Private and Final Methods in Java Methods in Java play an important role in making the code more readable, support code reusability, and defining the behaviour of the objects. And we can also restrict the methods based on requirements using the keywords and modifiers such as final and private. These two have different, distinct purp
5 min read
Naming Conventions in Java A programmer is always said to write clean codes, where naming has to be appropriate so that for any other programmer it acts as an easy way out to read the code. At a smaller level, this seems meaningless but think of the industrial level where it becomes necessary to write clean codes in order to
5 min read