TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Java For Loop Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java Flow ControlJava Tutorials

Java For Loop Explained

Last updated: Sep 30, 2023 6:34 pm
By Meenakshi Agarwal
Share
5 Min Read
For loop in Java
For loop in Java
SHARE

This tutorial will guide you on how to use a for loop in Java programs, perform repetitive tasks, and iterate through the elements of a collection or array. It is a core Java programming construct used to perform repetitive tasks.

Contents
The flow of a programSequential:Conditional:Iterative:For LoopDescription:Syntax:Flowchart:Advanced looping techniqueSyntax:Examples:Print numbers in a single line:Count backward from a given number:Iterate through a collection:

Basics of For Loop in Java

The tutorial has the following sections to help you learn quickly.

The flow of a program

The workflow of an application represents how the compiler executes the lines of your code. There are three basic types of flow in a Java program:

Sequential:

Sequential flow is the normal flow of execution. It means the very first instruction that will execute is line 1, then 2, and so on until the control reaches the end of your code.

Conditional:

Conditional flow occurs when the execution reaches a specific part in your code that has multiple branches. Here, the result of the condition decides the course of the program.

Java supports two conditional statements: if-else and Switch-Case.

Iterative:

Iterative flow comes into the light when the control enters a block which repeats itself for a specified number of cycles.

Java provides looping statements such as for, while, and do-while loops to achieve this effect. The user can decide how many times the block runs in the program.

Must Read – Variable in Java

For Loop

Description:

For loop provides the most straightforward way to create an iterative block. It has a three-instruction template where the first is to initialize the loop counter, the second is the condition to break, and the third increments the counter.

It is like a contract which makes all the terms and conditions pretty clear and visible. The for loop also gives the programmer the highest level of visibility over the number of iterations and the exit condition.

Syntax:

It has a cleaner and informative structure:

for (init counter; check condition ; move counter)
{
    statement(s);
}

As we said there are three statements in the for-loop. The first instruction tells when to start the loop; you initialize a variable here with some value.

The second statement is a condition which if evaluates to true; then the loop continues or else breaks.

In the next statement, you can move the counter both ways, i.e., increment or decrement its value.

e.g.

for (int iter = 0; iter <= 10 ; iter++)
{
    System.out.println("iter: " + iter);
}

The above loop will run 11 times printing numbers from 0 – 10.

Flowchart:

Check below is the for-loop flow diagram.

Java for loop flowchart

Also, Read – Data types in Java

Advanced looping technique

Java has one more style of “for” loop first included in Java 5. It lays down an easy way to traverse through the items of a collection or array. You should use it only for sequentially iterating an array without using indexes.

In this type, the object/variable doesn’t change, i.e., the array doesn’t change, so you can also call it a read-only loop.

Syntax:

for (T item:Collection obj/array)
{
    instruction(s)
}

Examples:

Print numbers in a single line:

public class MyClass {
    public static void main(String args[]) {
        int N = 5;
	    
        for (int iter = 0; iter < N; ++iter) {
            System.out.print(iter + " ");
        }
    }
}

Instead of writing the print statement for n times, we made the for loop resolve it. Here ‘iter’ is the loop control variable.

The output is as follows:

0 1 2 3 4

Count backward from a given number:

public class MyClass {
    public static void main(String args[]) {
        int N = 5;
	    
        for ( int iter = N; iter > 0; iter-- ) {
            System.out.print(iter + " ");
        }
    }
}

The result is as follows:

5 4 3 2 1

You can see that the “for” loop lets us manipulate the test condition and update the statement to yield different outputs.

Iterate through a collection:

public class MyClass 
{ 
   public static void main(String args[]) 
   { 
      String array[] = {"Python", "Java", "CSharp"}; 

      // Advanced for loop 
      for (String item:array) 
      { 
         System.out.print(item + " ");
      }
      
      System.out.println(" ");

      // Standard for loop 
      for (int iter = 0; iter < array.length; iter++) 
      { 
         System.out.print(array[iter] + " "); 
      }
   } 
}

After execution, the following values will print:

Python Java CSharp  
Python Java CSharp

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Operators in Java
Next Article Python Decorator Tutorial Decorators in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x