beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

For loop in Java with example

By Chaitanya Singh | Filed Under: Learn Java

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. In Java we have three types of basic loops: for, while and do-while. In this tutorial we will learn how to use “for loop” in Java.

Syntax of for loop:

for(initialization; condition ; increment/decrement)
{
   statement(s);
}

Flow of Execution of the for Loop

As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.
for loop Java

First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition is re-evaluated.

Example of Simple For loop

class ForLoopExample {
    public static void main(String args[]){
         for(int i=10; i>1; i--){
              System.out.println("The value of i is: "+i);
         }
    }
}

The output of this program is:

The value of i is: 10
The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation

Infinite for loop

The importance of Boolean expression and increment/decrement operation co-ordination:

class ForLoopExample2 {
    public static void main(String args[]){
         for(int i=1; i>=1; i++){
              System.out.println("The value of i is: "+i);
         }
    }
}

This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression: i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop would terminate at some point of time or not.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
    // statement(s)
}

For loop example to iterate an array:

Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 {
    public static void main(String args[]){
         int arr[]={2,11,45,9};
         //i starts with 0 as array index starts with 0 too
         for(int i=0; i<arr.length; i++){
              System.out.println(arr[i]);
         }
    }
}

Output:

2
11
45
9

Enhanced For loop

Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.

Let’s take the same example that we have written above and rewrite it using enhanced for loop.

class ForLoopExample3 {
   public static void main(String args[]){
      int arr[]={2,11,45,9};
      for (int num : arr) {
         System.out.println(num);
      }
   }
}

Output:

2
11
45
9

Note: In the above example, I have declared the num as int in the enhanced for loop. This will change depending on the data type of array. For example, the enhanced for loop for string type would look like this:

String arr[]={"hi","hello","bye"};
for (String str : arr) {
         System.out.println(str);
}

Check out these java programming examples related to for loop:

  1. Java Program to find sum of natural numbers using for loop
  2. Java Program to find factorial of a number using loops
  3. Java Program to print Fibonacci Series using for loop
❮ PreviousNext ❯

Comments

  1. Harsh bhatnagar says

    September 27, 2015 at 4:53 AM

    I really appreciate and recommend this website to all the beginners and experienced as well. As i find it very ease in learning java, i’ve been in touch with the same for past 1yr but never been so comfortable with it. But after reading the few tutorials on this website i realized that, my concepts weren’t that much clear which i feel have been cleared after hitting these tutorials.
    Thanks –

    Reply
  2. Sasidhar says

    November 12, 2015 at 7:11 AM

    Very Helpful for beginners…As I am from a Non-IT background in my graduation, this site has helped me a lot…Add more sample & simple programs so that we can know more.
    Great going guys…keep it up :)

    Reply
  3. shashi says

    June 25, 2016 at 3:52 PM

    I think this array declaration is wrong.it can’t be like this.
    int arr[4]={2,11,45,9};
    It should be like this
    int arr[]={2,11,45,9};

    Reply
    • Syed Bilal says

      September 2, 2016 at 7:19 PM

      Both ways are correct. He declared and FIXED the size of array to 4 and if I come to your point, you can declare any number of members in your array!. Your concept is good for Multidimensional Array but for Single array.. Always declare the size of array!.

      Reply
    • Dragica says

      November 24, 2016 at 9:39 AM

      That’s right!

      Reply
    • Wuu says

      November 26, 2016 at 12:10 PM

      thanks, your comment is helping me a lot.

      Reply
      • king says

        March 20, 2017 at 6:36 PM

        i think first one was right .
        You can right like this :
        int [] array = new int[4];
        array ={2,11,45,9};

        Reply
  4. azhar says

    March 30, 2017 at 2:56 AM

    I want a real life example. For all the loops can any one help me out

    Reply
  5. Unknown says

    June 15, 2017 at 6:37 PM

    This is one of the best sites for learning java. Concepts are made very clear and explained in such a simple way. Wonderful way of teaching. Thank you so much!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Index
  • Java Introduction
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Control Statements

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor
  • Java Interview Q

MORE ...

  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap