Java for loop infinite loop

Java Infinite For Loop

To make a Java For Loop run indefinitely, the condition in for statement has to be true whenever it is evaluated. To make the condition always true, there are many ways.

In this tutorial, we will learn some of the ways to create an infinite for loop. We shall learn these methods with the help of example Java programs.

Flowchart – Java Infinite For Loop

Following is the flowchart of infinite for loop in Java.

As the condition is never going to be false, the control never comes out of the loop, and forms an Infinite Loop as shown in the above diagram, with blue paths of execution.

Example 1 – Java Infinite For Loop with True for Condition

Firstly, we know that the condition in for loop statement has to always evaluate to true for it to become infinite Loop. Secondly, we also know that the condition evaluates to a boolean value. So, considering these two statements, we can provide the boolean value true , in place of condition, and the result is a infinite for loop.

Читайте также:  Working with forms in php

Java Program

/** * Java Program - Infinite For Loop */ public class InfiniteForLoop < public static void main(String[] args) < for (; true; ) < System.out.println("hello"); >> >

Note: You will see the string hello print to the console infinitely, one line after another. If you are running from command prompt or terminal, to terminate the execution of the program, enter Ctrl+C from keyboard. If you are running the program from an IDE, click on stop button provided by the IDE.

Example 2 – Java Infinite For Loop with Condition that is Always True

Instead of giving true boolean value for the condition in for loop, you can also give a condition that always evaluates to true. For example, the condition 1 == 1 or 0 == 0 is always true. No matter how many times the loop runs, the condition is always true and the for loop will run forever.

Java Program

/** * Java Program - Infinite For Loop */ public class InfiniteForLoop < public static void main(String[] args) < for (; 1 == 1; ) < System.out.println("hello"); >> >

Example 3 – Java Infinite For Loop with No Update to Control Variables

These type of infinite for loops may result when you forget to update the variables participating in the condition.

In the following example, we have initialized variable i to 10 . Typically, in the following example, one would decrement i to print hello 10 times. But, if we forget the decrement statement in the for loop update section, i is never updated. This makes the loop an infinite for loop.

Java Program

/** * Java Program - Infinite For Loop */ public class InfiniteForLoop < public static void main(String[] args) < for (int i = 10; i >0; ) < System.out.println("hello"); >> >

Conclusion

In this Java Tutorial, we learned how to write an Infinite For Loop in Java, with the help of example programs.

Источник

Infinite Loops in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’ll explore ways to create an infinite loop in Java.

Simply put, an infinite loop is an instruction sequence that loops endlessly when a terminating condition isn’t met. Creating an infinite loop might be a programming error, but may also be intentional based on the application behavior.

2. Using while

Let’s start with the while loop. Here we’ll use the boolean literal true to write the while loop condition:

public void infiniteLoopUsingWhile() < while (true) < // do something >>

3. Using for

Now, let’s use the for loop to create an infinite loop:

public void infiniteLoopUsingFor() < for (;;) < // do something >>

4. Using do-while

An infinite loop can also be created using the less common do-while loop in Java. Here the looping condition is evaluated after the first execution:

public void infiniteLoopUsingDoWhile() < do < // do something >while (true); >

5. Conclusion

Even though in most of the cases we’ll avoid creating infinite loops but there could be some cases where we need to create one. In such scenarios, the loop will terminate when the application exits.

The above code samples are available in the GitHub repository.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Loops in Java

Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

java provides Three types of Conditional statements this second type is loop statement .

  • while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.

Java

while loop

  • Flowchart:
    • While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason it is also called Entry control loop
    • Once the condition is evaluated to true, the statements in the loop body are executed. Normally the statements contain an update value for the variable being processed for the next iteration.
    • When the condition becomes false, the loop terminates which marks the end of its life cycle.
  • for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.

for (initialization condition; testing condition;increment/decrement)

Java

  • Flowchart:
    • Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
    • Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
    • Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
    • Increment/ Decrement: It is used for updating the variable for next iteration.
    • Loop termination:When the condition becomes false, the loop terminates marking the end of its life cycle.
  • do while: do while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.

Java

  • Flowchart:
    • do while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
    • After the execution of the statements, and update of the variable value, the condition is checked for true or false value. If it is evaluated to true, next iteration of loop starts.
    • When the condition becomes false, the loop terminates which marks the end of its life cycle.
    • It is important to note that the do-while loop will execute its statements atleast once before any condition is checked, and therefore is an example of exit control loop.

Pitfalls of Loops

  • Infinite loop: One of the most common mistakes while implementing any sort of looping is that it may not ever exit, that is the loop runs for infinite time. This happens when the condition fails for some reason. Examples:
  • Infinite for loop :

Java

infinite while loop:

Java

Java

Another pitfall is that you might be adding something into you collection object through loop and you can run out of memory. If you try and execute the below program, after some time, out of memory exception will be thrown.

Java

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Unknown Source) at java.util.Arrays.copyOf(Unknown Source) at java.util.ArrayList.grow(Unknown Source) at java.util.ArrayList.ensureCapacityInternal(Unknown Source) at java.util.ArrayList.add(Unknown Source) at article.Integer1.main(Integer1.java:9)

Nested Loop:

Nested loop means a loop statement inside another loop statement.

There are different combinations of loop using for loop, while loop, do-while loop.

Источник

Оцените статью