For Loop in Java
Learn via video course
Overview
Loops are used to run a block of code multiple times. In Java, there are three types of loops: for loops, while loops, and do-while loops. Using a for loop, which is a repetition control structure, you can quickly create a loop that has to run a certain number of times. For loops are of different types
- Simple For loop
- Nested For loop
- for each loop
- labeled for loop
- Java Infinitive for Loop
Scope
In this article, we are going to discuss
- What are for loops in java
- How to write for loops in java
- type of for loops in java
- simple for loops
- nested for loops
- For-each or Enhanced for Loop
- Labeled for Loop
- Java Infinitive for Loop
Introduction to Loops in Java
In certain circumstances, while programming, it becomes necessary to run a block of code multiple times. These statements generally carry out in the following order: A function's first statement is executed first, then the second, and so on. In this condition, loops are used.
The for loop, while loop, and do-while loop are the three types of loops available in Java. All three of these Java loop constructs carry out a series of repeated statements so long as a certain condition holds true.
Loop control is the common term for this certain condition. A true condition is one that produces a boolean value of true, while a false condition is one that returns a boolean value of false for all three loop statements. To learn more about the loop in java
For Loop in Java
A block of statements may be executed repeatedly with a set number of times based on the test expression or test condition using Java's for loop, an entry-controlled loop. The Java loops that are easy to comprehend are those.
While in other Java loop structures, the loop elements are dispersed across the program, but in for loop all of its loop-control elements are grouped at one location, on top of the loop within the round brackets().
Syntax
1.Initialization Expression(s)
It is an initial condition this is executed only once when the loop starts.
We must initialize a loop's control variable before starting it. Under the initialization expression, the control variable is initialized. The loop variable(s) are given their starting value. The loop's opening statement only ever executes the initialization phrase once.
2.Test Expression
It is the second condition that is executed every time to check/test the condition of the loop.
The test expression is a boolean expression whose truth value determines whether or not the body of the loop will be run. The test expression, also known as the exit condition or test condition, determines whether the loop will continue or end.
The body of the loop is executed if the test expression evaluates to true, or 1, otherwise the loop is ended.
The test expression is evaluated before entering a loop in an entry-controlled loop. If the test expression is evaluated before leaving a loop in an exit-controlled loop. For loops, while loops, and do-while loops are entry-controlled loops in Java, respectively.
3.Update Expression(s)
The loop variables' values are modified by the update expression(s). At the conclusion of the loop, after the body of the loop has been completed, the update expression is used. For instance, increment or decrement commands can be used as update expressions.
4.The Body of the Loop
The body of the loop is made up of the statements that run repeatedly (as long as the test expression does not equal zero). Depending on the result of the test expression, the loop's body's code will either run or not.
The loop body is continually run if the value evaluates to true; else, it is terminated.
Code Flow
Firstly the Initialization gets executed only once and the loop variable is initialized.
Then Test Expression tells for loop to run the loop as long as it is True. If the Test Expression returns False then break the loop
If Test Expression returns True then the Body of the loop gets executed.
After the body of the loop gets executed control back to update the Expression. This allows updating of loop variables.
The Test Expression is evaluated again if it's True then Body again gets executed else loop terminates.
Flow chart
Example
Example 1 In this example we are going to generate numbers from 1 to 9 using for loop.
Output
Code explanation
In the above code, Initialization Expression is int i=0 i is initialized with value 0. Test Expression is i<10 mean loop will run until i is less than 10.i++ is updated expression so i will increment after each iteration.
Example2
In this example, we are going to print numbers from 1-10 using for loop with multiple initialization and update.
Output
Code Explanation In Above Code we have initialized multiple variables sum and i and multiple update expressions sum+=i and ++i.
How to Write for Loop in Java
When you break it down into its essential parts, the syntax for writing a for loop in Java is rather simple and simple to comprehend. However, the for loop's initial appearance can be a little overpowering.
Syntax
You begin by using the keyword for, followed by two parentheses. You must then include the arguments between parentheses.
For Loop Arguments
The for loop takes the following three arguments to determine what behavior is expected of it.
- Initializer: The for loop is initialized with this argument at its default beginning point of zero.
- Condition
loop's termination is determined by the condition. Evaluating as true or false is how the conditional statement is evaluated. The cycle repeats itself until the condition is false. - Increment/Decrement
time the condition returns true, this increments or decrements the initializer by one.
Typically, a task is finished in the body of the for loop each time the condition returns true. There are no restrictions on the complexity of this assignment, which is known as the statement. There are countless possibilities for what you as a programmer can achieve with for a loop.
Example In this example, we are going to understand how to write a simple for loop by printing the square of a number from 0-10.
Output
First, the value of i gets initiated by value 0 then it checks if i<=10 that returns True so the loop body gets executed then in the body we have a printed square of 0. The value of i get updated and become 1 again i<=1 return True so the loop body gets executed and print 1. This process continues for i=10. Then after the value of i incremented to 11 i<=10 returned False and the loop got terminated.
Types of For Loops in Java
The for loop in Java can be used in a variety of ways, increasing its adaptability and flexibility. The next paragraphs cover the many for-loop versions.
1. Simple for Loop
The for loops that we discussed above are simple for loops. Loops having initialization,updation, test expression, and body are simple for loop.
Syntax
Example In this example, we are going to use simple for loop to print numbers from 1-10
Output
2. Java Nested for Loop
A loop is referred to as being nested when it contains another loop within its body. The inner loop, however, must come to an end before the outer loop in a nested loop. An illustration of a "nested" for loop is the following:
Syntax
Example In this example, we are going to print the * pattern using nested for loop.
Output
Code Explanation
In Above code first for i=1 inner loop will run 1 time and print single *.Then for i=2 inner loop will run 2 time and print * * for i=3 * * * and so on.
3. For-each or Enhanced for Loop
In Java 5, the for-each loop was first introduced. It's also known as an Enhanced for a loop.
It's a different traversing method created specifically to go across collections or arrays. Notably, the for is also used as a keyword. However, we assign a variable with the same type as an array or collection in place of utilizing a loop counter variable.
For-each refers to the process of iteratively traversing each element of an array or collection.
Example In this example, we are going to print each element of array num using for each loop.
Output
Code Explanation
In Above Code for loop will traverse through an array num and the number will store each of its elements in every iteration.
4. Labeled for Loop
When we wish to stop or continue a certain for loop in response to a need, labeling a for loop is helpful. A break statement inside an inner for loop will cause the compiler to exit the inner loop and restart the outer loop.
Labels can be used with break and continue. Labels allow you to shift control from the break and continue. In general, a break goes outside a loop, but if you have more than one loop, you can specify which loop you want to break by providing labels in the break statement.
Syntax
Example In the example below we are going to use the label for loop with nested for loop.
Output
Code Explanation In the above code In the innermost loop when j2=5 will print 5 and when j2=6 break will exit from the loop with the outermost label.
5. Java Infinitive for Loop
If a condition is always true, an infinite loop will result.
Example In this example, we are going to use an infinite loop that will print "Hello World" endlessly.
Code Explanation
This will print Hello World endlessly. Because the termination Condition is not specified
Code Explanation
The code above will start printing numbers at zero and never stop because a termination condition is not given.
More Examples
Loop With if and else In this example, we are going to use if and else condition with for loop that will print even and odd numbers from 0-9.
Output
Code Explanation In the above code if i is even will print i is even if odd print i is odd
Traverse array of string using for loop
In the code below we are going to print elements of a String array using a simple for loop.
Output
Code Explanation
In the above code by using for loop we are traversing the list of string names and printing each name.
Traversing arraylist using for each loop
In the Example Below we have used for each loop to print elements of ArrayList.
Output
Code Explanation By using for each loop we are traversing ArrayList of String.
Conclusion
- To run a block of code multiple times loops are used
- The for loop, while loop and do-while loop are the three types of loops available in Java.
- Using a for loop, which is a repetition control structure, you can quickly create a loop that has to run a certain number of times.
- For loops are of different types
- Simple For loop
- Nested For loop
- for each loop
- labeled for loop
- Java Infinitive for Loop