×

Java For Keyword

For as a keyword in java:

When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express the loop structure. For statement condenses the initialization, condition, and increment/decrement into a single line, making the looping structure shorter and simpler to troubleshoot.

Flowchart of For Loop

Java For Keyword

A section of the programming is repeatedly iterated using the Java for loop. Use of a for loop is advised if the number of iterations is fixed.

In Java, there are 3 different forms of for loops.

  1. Simple for Loop
  2. For-eachor Enhanced for Loop
  3. Labeled for Loop

Simple for loop

A straightforward for loop is equivalent to C/C++. We can set the variable to a value.

check the increment/decrement value and the condition. There are four sections to it:

  • Initializing in for loop:
    Step 1: When the loop begins, the first condition is the one that is run once. Here, we have the option of implementing the variable or using one that has already been initialised. It's an optional requirement.
  • Condition in for loop:
    Step 2: Every time the loop's state is tested, the second condition is what is carried out. Until the condition is false, execution keeps going. Either true or false must be returned as a boolean value. It's an optional requirement.
  • Increment or decrement step in for loop:
    Step 3: The variable value is increased or decreased as a result. It's an optional requirement.
  • Printing Statement:
    Every time the second condition is met, the loop's statement is carried out.

Syntax of for loop:

for (initialization; condition; increment/decrement) {    
//output or the statements that should be repeated to print or execute
}    

Example for a simple for loop Keyword:

ForExample.java


//Program in java to illustrate the example of for loop keyword
//mathamatic tables of 1 which is executed or printed
public class for_Ex {  
public static void main (String [] s) {  
    //Java for loop  
for (int i=1; i<=10; i++) {
        System.out.println(i);
    }  
}  
}  

Output:

1
2
3
4
5
6
7
8
9
10

Nested For Loop in Java

Nested for loops are for loops that are contained within other loops. Every time the outer loop runs, the inner loop also does.

Example:

Nested For Example in java programming language

public class Nested_For_Ex {  
public static void main (String [] s) {  
//loop of a
for (int a=1; a<=3; a++) {
//loop of b
for (int b=1; b<=3; b++) {
        System.out.println(a+" "+b);
}//end of a
}//end of b
}  
}  

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Pyramid Examples of java programming language using for loop:

Exmaple 1:

public class PyramidEx1{  
public static void main (String [] s) {  
for (int a=1; a<=5; a++) {
for (int b=1; b<=a; b++) {
        System.out.print("* ");
}  
System.out.println() ;//new line  
}  
}  
}  

Output:

* 
* * 
* * * 
* * * * 
* * * * *

Example 2:

public class PyramidEx2 {  
public static void main (String [] s) {  
int num=6;
for (int x=1; x<=num; x++) {
for (int y=num; y>=x; y--) {
        System.out.print("* ");
}  
System.out.println() ;//printing or executing a new line  
}  
}  
}  

Output:

* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*  

For each Loop in Java

Java's for-each loop is used to iterate across an array or collection. Because we don't have to use subscript notation or increment value, it is simpler to use than a standard for loop.

Instead, then using an index, it operates based on elements. In the specified variable, each element is returned one by one.

Syntax:

for (data_type variable: array_name) {
//output printing statements
}    

Example:

//array elements of the program
public class ForEachEx {  
public static void main (String[] s) {  
    //initializing an array statically
    int ele[] = {12,23,44,56,78};
    //executing the array by implementing the for-each loop  
for (int a: ele) {
        System.out.println(a);
    }  
}  
}  

Output of the program:

12
23
44
56
78

Java Labeled for Loop

Each Java for loop can have a name. We utilize label before the for loop to do this. We may break/continue a particular for loop, which is helpful when utilizing nested for loops.

Syntax:

labelname:    
for (initialization; condition; increment/decrement) {
//executing statements
}    

Example:

public class LabeledforEx {  
public static void main (String[] s) {  
gg:  
for (int a=1; a<=3; a++) {
hh:  
for (int b=1; b<=3; b++) {
                    if(a==2&&b==2) {
                        break gg;
                    }  
                    System.out.println(a+" "+b);
                }  
        }  
}  
}  

Output:

1 1
1 2
1 3
2 1

Infinity For Loop in Java

The for loop becomes infinite if two semicolons are used, or ;;

Syntax:

for (;;)
{
// statements
}

Example:

public class ForEx {  
public static void main (String [] s) {  
    //no implemetation of condition in for loop  
for (; ;) {
        System.out.println("loop is continuous");
    }  
}  
}  

Output of the program:

loop is continuous
loop is continuous
loop is continuous
loop is continuous
loop is continuous

Related Topics

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Aggregation in Java

Aggregation A "has-a" and "whole/part" connection is the best way to define the aggregate relationship in Java, which exists between two classes. This connection relationship has a higher level of specialisation....

4 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java Applications

The growth in technology is increasing rapidly, so some languages are used for developing them. Java is one such famous programming language which is having numerous applications. The Java Programming...

4 minutes read.