Java Demo

Loop statements

Java Demo / Loop statements

Loop statements

For Loop

The for loop in Java is used to execute a block of code repeatedly for a fixed number of times. It is commonly used when the number of iterations is known in advance.

In a for loop, initialization, condition checking, and increment/decrement are written in a single line, which makes the code clean and easy to read.

Example

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

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

for-each loop

The for-each loop in Java is an enhanced version of the for loop used to iterate through arrays and collections in a simple way. It allows accessing each element one by one without using an index or manually controlling the loop counter.

The loop automatically moves from the first element to the last element, making the code easier to write and read.

 

Example

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

       int numbers[] = {10, 20, 30, 40, 50};

       for (int num : numbers) {
           System.out.println(num);
       }
   }
}

Technology
Java Demo
want to connect with us ?
Contact Us