Java For Loop

If you are new for java8 and want to install java8 on your machine, please follow the tutorial.

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. 

There are three types of basic loops in Java: for, while, and do-while. In this tutorial, We will learn how to use "for loop" in Java.
 Syntax :
for(initialization; condition test; expression/increment/decrement) { statement(s); }

Java For Loop Example

  • Part One: Initialization Use this part to declare and Initialize a variable to use within the loop body. You'll most often use this variable as a counter. You can actually initialize more than one variable here, but we'll get to that later In the book.
  • Part Two: boolean test This Is where the conditional test goes. Whatever's In there, It must resolve to a boolean value. You can have a test" like (x >= 4), or you can even Invoke a method that returns a boolean.
  • Part Three: IteratIon expression In this part,put one or more things you want to happen with each trip through the loop. Keep In mind that this stoff happens at the end of each loop
  • Increment/ Decrement: It is used for updating the variable for the next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
// Java program to explain for a loop.

Java For Loop

Example 
package com.javacodestuffs.core.loops; class forLoopExample { public static void main(String args[]) { public static void main(String args[]) { for (int i = 2; i < 8; i++) { System.out.println(i);} System.out.println("Done!!!"); } } output: $javac com/javacodestuffs/core/loops/forLoopExample.java $java -Xmx128M -Xms16M com/javacodestuffs/core/loops/forLoopExample 2 3 4 5 6 7 Done!!!

Sum of Number using for loop

package com.javacodestuffs.core.loops; public class CalculateSum { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 100; ++i) { sum += i; // sum = sum + i } System.out.println("Sum of first 100 numbers is : " + sum); } } output: $javac com/javacodestuffs/core/loops/CalculateSum.java $java -Xmx128M -Xms16M com/javacodestuffs/core/loops/CalculateSum Sum of first 100 numbers is : 5050

Here, we have a variable named sum. Its initial value is 0. Inside for loop,
we have initialized a variable named i with value 1.
In each iteration of for loop,
1). The sum variable is assigned value: sum + i
2). The value of i is increased by 1
3). The loop continues until the value of i is greater than 1000. For better visualization,

Infinite for Loop

Sometimes by mistake, we forgot to break loop on certain conditions.results for loop become infinite for loop.
the programmer needs to take care in such cases, need to break loops using the break statement or if loop.


Here is an example of an infinite for loop.

package com.javacodestuffs.core.loops; public class InfiniteForLoop { public static void main(String[] args) { int sum = 0; for (int i = 1; i <= 10; --i) { System.out.println("This is an infinite loop...never use like this."); } } } or for ( ; ; ) { }

Pyramid using for loop

package com.javacodestuffs.core.loops; public class PyramidUsingForLoop { public static void main(String[] args) { for (int i = 1; i <= 7; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } } } output: * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Reverse Pyramid using for loop

package com.javacodestuffs.core.loops; public class ReversePyramidUsingForLoop { public static void main(String[] args) { for (int i = 1; i <= 7; i++) { for (int j = 7; j >= i; j--) { System.out.print("* "); } System.out.println(); } } } output: * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Java for-each Loop

To work with Java arrays and Collection we need this kind of loop.
Here is the example to calculates the sum of all elements of an int array.

Syntax: for(dataType item : collections) { ... }

collection - a collection or array that you have to loop through. item - a single item from the collections.

Advantages:
1). for-each loop is easier to write and makes our code more readable.
2). We can Iterate through the elements in a sequential manner without knowing the index of the currently processed elements.

Disadvantages:
The object/variable is immutable when enhanced for loop is used i.e
it ensures that the values in the array can not be modified, so it can be said as read only loop
where you can’t update the values as opposite to other loops where values can be modified.

How the for-each loop works?
Here's how the for-each loop works in Java. For each iteration, the for-each loop
1). Iterates through each item in given collections or arrays
2). Stores each item in a variable (item)
3). Executes the body of the loop.

package com.javacodestuffs.core.loops; public class EnhancedForLoop { public static void main(String[] args) { int[] numbers = {11,55,2533, 44, 15, 1, 10, 22,9}; int sum = 0; for (int number: numbers) { sum += number; } System.out.println("Sum of numbers inside array is : " + sum); } } output: $javac com/javacodestuffs/core/loops/EnhancedForLoop.java $java -Xmx128M -Xms16M com/javacodestuffs/core/loops/EnhancedForLoop Sum of numbers inside array is : 2700

Questions related to Java For Loop

How to use in java Strings using for loop?
What is the Syntax for While loop in Java?
How to get a value from for loop in java?
How to print 1 to 100 with a loop in java?
What is the Syntax for While loop in Java?

In this article, we have seen the  Java for loop with examples. All source code in the article can be found in the GitHub repository.