JAVA TUTORIAL

Java Intro Java Features Java vs C++ Java Simple Program Java Applet vs Application JVM,JDK or JRE Java Keywords Java Variables Java Literals Java Separators Java Datatypes Java Operators Java Statements Java Array Java String

CONTROL STATEMENTS

Java If-else Java While Loop Java Do-While Loop Java For Loop Java For-each Loop Java Switch Java Break/Continue

JAVA METHODS

Java Method Java Overloading Java Overriding

JAVA CLASSES

Java OOPs Java Classes/Objects Java Inheritance Java Polymorphism Java Encapsulation Java Abstraction Java Modifiers Java Constructors Java Interface Java static keyword Java this keyword

Java for Loop

In this tutorial, we will learn how to use for loop in Java with the help of examples.

In computer programming, loops are used to repeatedly execute a block of statements. For example, if you want to print message 100 times, then rather than typing the same code 100 times, you can use a loop.

There are three types of loops in Java:

1. for loop

2. while loop

3. do-while loop

Java for Loop

In java for loop is used to run a block of code for a certain number of times. It is particularly used in cases where the number of iterations is fixed.

The for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.

Syntax:

for(initialization expr; condition expr; update exp){
// body of the loop
// statement or code to be executed
}

Example:

// Java program to print number form 1 to 10

class Simple{
    public static void main(String args[]){

    for(int i = 1; i <= 10; i++){
        System.out.println(i);
    }
    }
}

Output:

1
2
3
4
5
6
7
8
9
10

Example 2: Display a Coder Ten Times

class Simple{
    public static void main(String args[]){

    for(int i = 1; i <= 10; i++){
        System.out.println("Coder");
    }
    }
}

Output:

Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder
Coder

Java Infinite For Loop

If we set the test expression in such a way that it never evaluates to false, the for loop will run forever. This is called infinite for loop.

Example:

// Infinite for Loop

class Simple{
    public static void main(String args[]){

    for(int i = 0; i <= 1; i--){
        System.out.println(i);
    }
    }
}

Output:

0
-1
-2
-3
-4
-5
-6
-7
.
.
.
ctrl+c

Note: ctrl+c is used for stop the execution of this program and exit form the program.