×

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

Rectangular Numbers in Java

In this tutorial, we will understand the meaning of a rectangular number in Java with the aid of examples, illustrations, and implementations. It is one of the popular coding interview...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 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 copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

How to Create Immutable Classes in Java

Introduction Java is a programming language that is entirely object-oriented, and everything in it is seen as an object. And the blueprint or template of these objects are classes. Several classes...

3 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.