Infinite For Loop Java Example

www‮‬.lautturi.com
Infinite For Loop Java Example

An infinite loop is a loop that continues indefinitely because the loop condition is always true. Here is an example of an infinite loop in Java using a for loop:

public class InfiniteForLoopExample {
    public static void main(String[] args) {
        for (;;) {
            // This loop will run forever because the loop condition is always true
            System.out.println("Hello, World!");
        }
    }
}

In this example, the loop condition is simply two semicolons, which is always true. As a result, the loop will run indefinitely, printing "Hello, World!" over and over again.

It is important to be careful when using infinite loops, as they can cause your program to hang or crash if not used correctly. If you need to create a loop that runs a certain number of times, it is better to use a while loop or a for loop with a fixed loop condition.

Here is an example of a for loop that runs 10 times:

public class FiniteForLoopExample {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            // This loop will run 10 times
            System.out.println("Hello, World!");
        }
    }
}

Output:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Created Time:2017-11-01 22:29:43  Author:lautturi