For Loop Java Syntax & Examples
In this article, we are going to learn about loops in Java programming language. We are using loops to execute some set of statements continuously until a particular condition is satisfied.
In Java we have three types of loops: For Loop, While Loop and do-while loop. But in this article, we are going to learn about the for loops in Java and the other loop we have discussed in a separate post, and you can follow this links for learning While Loop in Java and Do-while loop in Java.
Loops are those who make the computers an interesting machine. Because suppose you want to print a message for ten times then, in that case, you can write ten-print statements but when you require to print for 1 million times, then that time loop statements helps you lot to achieve your requirement quickly.
do-while or while loop used when we do not know how many times we have to execute the statements. It just depends on the condition. the execution should continue until the condition is false. But this loop is more suitable for a situation where the statements should execute a fixed number of times. Here in for loop, we know how many times exactly we want to execute.
for loops Syntax
for (initialization; condition; increment / decrement) { // Loop body statements }
The flow of Execution of the for Loop
- In this type of loop, the initialisation is happening for only one time, that means the initialisation part execute only one time.
- The condition evaluated for each iteration. If the condition is true, then the execution will enter into the loop body area and execute the statements, and if the condition gets failed, then the flow of execution comes out of the loops. The statements which are present outside of the loop body will execute.
- In each execution of the loop, the loop body and the increment/decrement part of the loop will execute. And the behaviour that is increment or decrement of the values as per the mentioned in the syntax.
- After increment/decrement execute, the execution jumps to the condition. It re-evaluates, if the condition is true, then the loop body statements will be executed, and if the condition failed, then the execution comes out from the loop body statements.
Simple for loop
package java_Basics; public class ForLoop_Example { public static void main(String[] args) { for (int i = 1; i <= 10; ++i) { System.out.println("Value Of I Is:- " + i); } } }
Output:
Value Of I Is:- 1 Value Of I Is:- 2 Value Of I Is:- 3 Value Of I Is:- 4 Value Of I Is:- 5 Value Of I Is:- 6 Value Of I Is:- 7 Value Of I Is:- 8 Value Of I Is:- 9 Value Of I Is:- 10
infinite for Loop
If the test condition is never false, then the loop will run forever. This type of loop is called an infinite loop. Here is below an example of an Infinite loop:
package java_Basics; public class InfiniteForLoop_Example { public static void main(String[] args) { for (int i = 1; i <= 10; --i) { System.out.println("Hello"); } } }
Java for-each Loop (Enhanced for Loop)
This is another form of for loop which is mainly used to work with Arrays and collection. If you are continuously working with arrays and collection, then you can implement or use for each loop as an alternative of for loop to iterate the items of arrays or collection.
Let’s take a syntax of an for each loop
for(data_type item : collection) { // For Each Loop Statements }
Lets us try to understand the difference between a for loop and for each loop with some simple examples:
For Loop:
Suppose we want to print all the elements of an character array, then we can print the elements in 2 ways that is by using for loop and for each loop.
package java_Basics; public class ForLoopExample_ForEach { public static void main(String[] args) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; for (int i = 0; i < vowels.length; ++ i) { System.out.println(vowels[i]); } } }
For Each Loop:
We can also print the same elements with using For Each loop like below:
package java_Basics; public class ForEachLoop_Example { public static void main(String args[]) { char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // foreach loop for (char item: vowels) { System.out.println(item); } } }
Key Points of For each loop
- It starts with the keyword for like we are using in for loop
- Instead of initialisation, condition and increment/decrement, here we need to declare the data type of an array or collection, followed with the array or collection name.
- In the loop body, you can use the item or loop variable instead of the index array element.
- For each loop is preferred when you are working with arrays or collection.
How for Each loop work
The for-each loop works in below way:
- It iterates each item in the given collection or array.
- Stores each item in a variable (item)
- Executes the body for each loop.
Limitations of the for-each loop
- for each loop is not appropriate when you want to modify the array.
- For each loop iterate elements one by one so we never get the index of the element.
- Using the for-each loop, we can not iterates elements from a specific position.
- Using the for-each loop, we cannot process two decision making statements at once.
If you find anything wrong in the post or if you want to add more information on this post, then you can inform us by writing in the comment section.
Ref: Oracle
In this program, we are going to how to reverse a sentence in the same order
package com.SoftwareTestingO.Java.basics; public class ReverseStringEx { public static void main(String[] args) { String str = "i am a programmer"; //o/p "r em m argorpamai"; String stringNoSpace = str.replaceAll("\\s", ""); String retString = ""; int end = stringNoSpace.length()-1; for(int i=0; i<str.length(); i++) { if(str.charAt(i)==' '){ retString += " "; }else{ retString += stringNoSpace.charAt(end); end--; } } System.out.println(retString); } }
Output:
r em m argorpamai
Leave a Reply