There is no difference in bytecode between while(true) and for(;;) but I prefer while(true) since it is less confusing (especially for someone new to Java).

You can check it with this code example

void test1(){
    for (;;){
        System.out.println("hello");
    }
}
void test2(){
    while(true){
        System.out.println("world");
    }
}

When you use command javap -c ClassWithThoseMethods you will get

  void test1();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #21                 // String hello
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

  void test2();
    Code:
       0: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #31                 // String world
       5: invokevirtual #23                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8: goto          0

which shows same structure (except "hello" vs "world" strings) .

Answer from Pshemo on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › infinite loops in java
Infinite Loops in Java | Baeldung
January 8, 2024 - Now, let’s use the for loop to create an infinite loop: public void infiniteLoopUsingFor() { for (;;) { // do something } } An infinite loop can also be created using the less common do-while loop in Java.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › infinite loop in java
Mastering Infinite Loop in Java: A Comprehensive Guide with Examples
2 weeks ago - To resolve this issue, ensure that the loop control variables are modified appropriately to satisfy the termination condition. The `do-while` loop guarantees that the loop block executes at least once, but it can also lead to infinite loops.
Discussions

Java: Infinite Loop Convention - Stack Overflow
What is the convention for an infinite loop in Java? Should I write while(true) or for(;;)? I personally would use while(true) because I use while loops less often. More on stackoverflow.com
🌐 stackoverflow.com
halting problem - Infinite loops in Java - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Look at the following infinite while loop in Java. More on stackoverflow.com
🌐 stackoverflow.com
Infinite While Loop in Java - Stack Overflow
Hey there! I'm trying to do some data input validation but I haven't been able to figure it out. I'm getting an infinite while loop in when I try to validate if the first character entered is a l... More on stackoverflow.com
🌐 stackoverflow.com
November 7, 2011
[Java] Unsure how to fix infinite loop
The issue is the consecutive b chars and the fact that you're decrementing i. It will keep looping back and forth between the consecutive b chars incrementing on the first one, then decrementing on the next one, which sets i to point back at the first one. You really just need to use a debugger and step through your code if you don't understand it. Additionally I would brush up on programming fundamentals before attempting leetcode. If you can't answer why your code is doing something on your own, you're not ready to do leetcode. More on reddit.com
🌐 r/learnprogramming
4
1
August 17, 2021
People also ask

How can I terminate or break out of an infinite loop in Java?
A: There are several ways to break out of an infinite loop, such as using the `break` statement, modifying loop variables, or using conditional statements to exit the loop.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › infinite loop in java
Mastering Infinite Loop in Java: A Comprehensive Guide with Examples
What problems can arise from infinite loops in a Java program?
A: Infinite loops can cause programs to hang, consume excessive resources, and prevent further execution of code.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › infinite loop in java
Mastering Infinite Loop in Java: A Comprehensive Guide with Examples
How can I handle intentional infinite loops to prevent unwanted consequences?
A: Intentional infinite loops should always include termination conditions or mechanisms to break out of the loop based on specific criteria.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › infinite loop in java
Mastering Infinite Loop in Java: A Comprehensive Guide with Examples
🌐
Scaler
scaler.com › home › topics › infinite loop in java
Infinite Loop in Java - Scaler Topics
July 7, 2024 - If we try to run the above code, the code will print Hello World as the while loop keeps on executing for infinite time. IMPORTANT: If there is a time limit on the period of execution, TimeLimitExceeded error will be thrown. Let's have a brief recap of for loop in Java, the initialization expression is used to initialize the counter, and the condition expression tests whether we have to execute the body of the for loop or we have to terminate the loop.
🌐
Tutorjoes
tutorjoes.in › Java_example_programs › implement_infinite_loop_using_do_while_loop_in_java
Write Java program to Implement infinite loop using do-while loop
This Java program is an example of an infinite loop that prints the word "Java" continuously. The loop condition · while(true) always evaluates to true, meaning the loop will never exit. The · do-while loop ensures that the code block inside the loop will execute at least once, and then the ...
🌐
Javaprogramto
javaprogramto.com › 2020 › 12 › create-infinite-loops-java.html
Creating Infinite Loops In Java JavaProgramTo.com
December 10, 2020 - * * @author javaprogramto.com * ... { // core logic System.out.println("Running loop"); } } } Next, use the while loop with true boolean in condition....
Find elsewhere
🌐
AlgoCademy
algocademy.com › link
Infinite While Loops in Java | AlgoCademy
In this lesson, we will explore the concept of infinite while loops in Java. Understanding how to control loops is crucial for writing efficient and bug-free code. Infinite loops can cause programs to become unresponsive and consume unnecessary resources, making it essential to know how to avoid them. Infinite loops are particularly significant in scenarios where the loop's termination condition is not correctly defined or updated. This can happen in various applications, such as data processing, user ...
🌐
Medium
medium.com › @AlexanderObregon › avoiding-and-understanding-infinite-loops-in-java-b3a294d11a47
Avoiding and Understanding Infinite Loops in Java
August 26, 2024 - Infinite loops are a common problem that many developers encounter, especially when first learning to code. An infinite loop occurs when a loop continues to execute without ever meeting the condition that should stop it.
🌐
Javatpoint
javatpoint.com › post › infinite-loop
Infinite Loop - Javatpoint
Infinite Loop with if-else, switch case, for loop, while loop, do-while, break, continue, goto, arrays, functions, pointers, collections, LinkedList, etc.
🌐
PrepBytes
prepbytes.com › home › java › infinite loop example in java
Infinite Loop Example in Java
January 31, 2023 - In the case of a while loop, we can pass true as the condition to execute the while loop indefinitely, in the case of a for loop, we can leave the expression empty to perform the for loop indefinitely, and in the case of a do-while loop, we ...
Top answer
1 of 4
4

You don't have an input = keyboard.nextLine(); in your second while loop.

You could refactor your code to only ask for new input when there is an error. So right after the sysout of 'ERROR...'

Extra: I would actually do this different. The 'error = true' at the beginning is a bit confusing, because there might not be an error.

You could for example write a method called tryProcessLine, which reads the input and returns true if ok and false if there was an error, and than just do something like while(!tryProcessLine()){ }

Working example below:

import java.io.IOException;
import java.util.Scanner;

public class Methods {

  private static int qoh;

  public static void main(String args[]) throws IOException {

    while (!tryProcessLine()) {
        System.out.println("error... Trying again");
    }

    System.out.println("succeeded! Result: " + qoh);

  }

  public static boolean tryProcessLine() {

    String input = "";

    Scanner keyboard = new Scanner(System.in);

    System.out.print("\nEnter Quantity on Hand: ");

    input = keyboard.nextLine();

    try {
        qoh = Integer.valueOf(input);

        if (qoh < 0 || qoh > 500) {
          System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
          return false;
        } else {
          return true;
        }
    } catch (NumberFormatException e) {
        System.out.println("\n**ERROR06** - Quantity on hand must be numeric");
        return false;
    }
  }
}
2 of 4
1

The problem is in this section:

                        while (error==true)
                        {
                            if (Character.isLetter(input.charAt(0)))
                            {
                                System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                error=true;
                                System.out.println(qoh);
                                System.out.println(input);
                            }
                            else
                            {
                                qoh = Integer.parseInt(input);
                                error=false;
                            }
                        }

Once you have a letter in the first position, this loop can never terminate. It checks whether a letter is in the first position (it is), prints it, and repeats. Try changing to:

                            while (error==true)
                            {
                                if (Character.isLetter(input.charAt(0)))
                                {
                                    System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                    error=false;

                                    ...

Also, a couple of other things:

while (error == true) can be shortened to while(error).

Also, Integer.parseInt will throw a NumberFormatException if the input is not an integer - you need to catch and handle this.

Also, why do you need the second loop at all? It seems like it is only supposed to validate the input - if so, you can move this logic into the first loop and eliminate the second one. Only use loops for things that should happen repeatedly (like the user entering input data). There is no need to check the same input repeatedly.

🌐
Quora
quora.com › Is-it-possible-to-make-an-infinite-loop-in-Java-without-using-recursion-If-yes-how-do-you-do-it-and-if-no-why-not
Is it possible to make an infinite loop in Java without using recursion? If yes, how do you do it and if no, why not? - Quora
Just stick this bit of code in any part of your program that will be called on runtime: [code]while (true) {} [/code]Because you see, what I did there isn’t recursion, which is defined as a function repeatedly calling itself until a base condition ...
🌐
Quora
quora.com › How-do-I-code-infinite-loop-in-Java
How to code infinite loop in Java - Quora
In this tutorial, I will show you how to write an infinite loop in Java using for and while loop. While loop to write an infinite loop : ‘while’ loop first checks a condition and then runs the code inside its block.
🌐
Quora
quora.com › How-can-I-write-a-Java-DO-while-in-infinite-loop
How to write a Java DO while in infinite loop - Quora
Answer (1 of 6): First of all this ... [/code]To write a java Do while infinite loop you need to make sure your condition in the Boolean expression stays true forever....
🌐
Udemy
blog.udemy.com › home › java while loops, do-while loops, and infinite loops
Java While Loops, Do-While Loops, and Infinite Loops - Udemy Blog
December 4, 2019 - This would continue subtracting 1 from num, down into the negative numbers, keeping its value less than 10, forever. This is an infinite loop because our boolean will always remain true, meaning our program will continue to run it with no end in sight, unless we fix it. This has been a basic tutorial on while loops in Java to help you get started.
🌐
Reddit
reddit.com › r/learnprogramming › [java] unsure how to fix infinite loop
r/learnprogramming on Reddit: [Java] Unsure how to fix infinite loop
August 17, 2021 -

I'm solving this LeetCode exercise but I'm caught with a issue.

I came across the test case for input "dvdf" where my output was incorrect. I realized that my code behaved this way incrementally:

  • 'd': Not in set, so add to set. Increment i

  • 'v': Not in set, so add to set. Increment i

  • 'd': Already in set, so clear set. (Do NOT increment i)

  • 'd': Not in set, so add to set. Increment i

  • 'f': Not in set, so add to set. Increment i

The correct longest substring without duplicates for "dvdf" is "vdf" but my resulting set was {d, f}. I realized that I had skipped reevaluating 'v', so I added i-- to my else-statement.

However, after adding this I got a timeout for an earlier test case "abcabcbb" where the set gets loops between {} and {b}.

I could totally just look at a solution, but I first want to know what I'm doing wrong so I can learn from it. Any help would be great. Thank you!

	class Solution {
		public int lengthOfLongestSubstring(String s) {
			
			HashSet<Character> set = new HashSet<>();
			int max_size = 0;
			
			int i = 0;
			while(i < s.length()){
				if(!set.contains(s.charAt(i))){
					set.add(s.charAt(i));
					i++;
				} else {
					set.clear();
					i--;
				}
				
				if(set.size() > max_size){
					max_size = set.size();
				}
			}
			
			return max_size;
		}
	}
🌐
Reddit
reddit.com › r/javahelp › having issues with infinite loops in java
r/javahelp on Reddit: Having issues with infinite loops in Java
June 8, 2022 -

Hello I am a high school student making a wordle program for my assignment, I've used an infinite loop for the method of my game but I'm having issues while using if statements in this loop. I've used "continue;" everywhere I think I can but it still prevents my code from repeating. I'm sorry if my code looks messy, things worked even less when I had methods because you can use "continue;" in a method that goes into a loop. The loop just refuses to continue even with "continue;" in my if statements me, my teacher and my classmates cannot think of a solution.

import java.util.; import java.io.; public class MyProgram{ //create default text colour public static final String ANSI_RESET = "\u001B[0m"; //create green text public static final String ANSI_GREEN = "\033[0;32m"; //create yellow tenxt public static final String ANSI_YELLOW = "\033[0;33m"; //create black backgound public static final String BLACK_BACKGROUND = "\033[40m"; //create yellow background public static final String YELLOW_BACKGROUND = "\033[43m"; //create scanner class object Scanner s = new Scanner(System.in); public static void main(String[] args){ //create array of 5 letter words String[] wordBank = {"storm","green","glass","mould","sweet", "stamp"}; //invoke user prompt userPromt(); //will store a random number from rng method int rng = rng(); //will store index of the word bannk with the same value of the RNG number String wordle = wordBank[rng]; //invoke game method game(wordle); } //will prompt user and tell them the rules static void userPromt(){ System.out.println("Welcome to Wordle! The goal of the game is"); System.out.println("to guess a randomly chosen 5 by guessing with "); System.out.println("5 letter words. For your guesses you"); System.out.println("recieve hints on your letters. Yellow means that the letter is"); System.out.println("in the word but not in the right place, green"); System.out.println("means that the letter you guessed is in the"); System.out.println("right place! Just keep trying your guesses."); System.out.println("Good luck and have fun!!," + YELLOW_BACKGROUND + ":)" + ANSI_RESET); } //wll generate a random number static int rng(){ //max for rng int max = 5; //minimum for rng int min = 0; //will generate the random number int randomNumber = (int)(Math.random() * (max - min + 1) + min); //will return the random number return randomNumber; } //will have game static void game(String wordle){ //create scanner class object Scanner s = new Scanner(System.in); //while tru will run methods for the game //counter int i = 0; System.out.println("Enter a word: "); //never use an infinite loop again... while(true){ //scan for user input String guessRaw = s.nextLine(); //convert to lowercase String guess = guessRaw.toLowerCase(); //counter increments after guess i++;

        //if guess is less than 5 letters or more than 5 letter print invalid guess message
        if (guess.length() < 5 || guess.length() > 5){
            //error message for user
            errorMessage();
            i--;
            //tell loop to continue
            continue;
        }

//This is about where my code gets loopy with all the continue statements and stuff, //will print hints //create for loop which will loop the if statments and their checks for (int o = 0; o < 5; o++){ //create variables to make if staments look neater and easier to read char guessChar = guess.charAt(o); char wordleChar = wordle.charAt(o); //will print g letters if character from i index on guess and wordle are the same if (guessChar == wordleChar){ System.out.print(ANSI_GREEN + guessChar + ANSI_RESET); //tell loop to continue continue; } //Will check for yellow letters if above condition is not true else if (guessChar != wordleChar){ //create for loop which will loop for staments and their checks for (int n = 1; n < 5; n++){ //create vaiable to make if statment look better char wordleCheck = wordle.charAt(n); //this loop will print one yellow character regardless of the number of matches found while(true){ //if guess character is found with a match it will print a yellow character if (guessChar == wordleCheck){ System.out.print(ANSI_YELLOW + guessChar + ANSI_RESET); break; } else{ continue; } } } continue; }

//Issue ends here

            //will print black letters if all other conditions false
            else {
                System.out.print(guessChar);
                continue;
            }
        }                
        //will print win message if conditions prove true
        //loop will check for letters guessed correctly add and to counter n
        for (int l = 0; l < 5; l++){
            int n = 0;
            char guessChar = guess.charAt(l);
            char wordleChar = wordle.charAt(l);
            if (guessChar == wordleChar){
                n++;
                //just for good measure
                continue;
            }
            //if the value of counter n reaches 5 the user wins the game.
            if(n == 5){
                System.out.println("You win! " + YELLOW_BACKGROUND + ":)" + ANSI_RESET);
                break;
            }
        }
        //will lose the gamne if user does not win after 6 guesses
        //THIS ACTIVATES IF YOU WIN FOR SOME REASON?!?!?!?!
        if (i >= 6){
            lose(wordle);
            break;
        }
    }
}
//error message for if guess word has wrong lenght
static void errorMessage(){
    System.out.println("Word length invalid.");
}
//method 
static void printHints(String guessString, String wordleString){
    //create for loop which will loop the if statments and their checks
    for (int i = 0; i < 5; i++){
        //create variables to make if staments look neater and easier to read
        char guess = guessString.charAt(i);
        char wordle = wordleString.charAt(i);
        //will print g letters if character from i index on guess and wordle are the same
        if (guess == wordle){
            System.out.print(ANSI_GREEN + guess + ANSI_RESET);
        }
        //Will check for yellow letters if above condition is not true
        else if (guess != wordle){
            //create for loop which will loop for staments and their checks
            for (int n = 1; n < 5; n++){
                //create vaiable to make if statment look better
                char wordleCheck = wordleString.charAt(n);
                //this loop will print one yellow character regardless of the number of matches found
                while(true){
                    //if guess character is found with a match it will print a yellow character
                    if (guess == wordleCheck){
                        System.out.print(ANSI_YELLOW + guess + ANSI_RESET);
                        break;
                    }
                }
            }
        }
        //will print a black letter if all other conditions are false
        else {
            System.out.print(guess);
        }
    }
    //will move cursor to the next line to make things look more organized
    System.out.println("");
}
//Will print losing message
static void lose(String wordle){
        System.out.println("You lose, the wordle was " + wordle);
}
//Will check for win conditions then print out win message
static void win(String guessString, String wordleString){
    //loop will check for letters guessed correctly add and to counter n
    for (int l = 0; l < 5; l++){
        int n = 0;
        char guess = guessString.charAt(l);
        char wordle = wordleString.charAt(l);
        if (guess == wordle){
            n++;
        }
        //if the value of counter n reaches 5 the user wins the game.
        if(n == 5){
            System.out.println("You win! " + YELLOW_BACKGROUND + ":)" + ANSI_RESET);
        }
    }
}
static void infiniteLoopie(char guessChar, char wordleChar, char wordleCheck){
    //this loop will print one yellow character regardless of the number of matches found
    while(true){
        //if guess character is found with a match it will print a yellow character
        if (guessChar == wordleCheck){
            System.out.print(ANSI_YELLOW + guessChar + ANSI_RESET);
            break;
        }
        else{
            continue;
        }
    }
}

}

Here is a Pastebin with my code: https://pastebin.com/SPmTJJyj

Honestly I cannot think of a solution other than use a for loop instead but I would rather like to keep as infinite it and I just came here to see if there was something I was doing wrong or could do to fix it.

I'm making this thread on my phone so I'm sorry if things get formatted weirdly because of it, if it gets removed I will go onto my PC and try to make it proper

Top answer
1 of 3
2
Can you refer which infinite loop are you asking about (line number) and what do you expect it to do? (Ideal case would be if you rather created a minimal reproducible example )
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
TutorialsPoint
tutorialspoint.com › can-a-for-statement-loop-infinitely-in-java
Can a for statement loop infinitely in java?
July 30, 2019 - You can run a for loop infinitely by writing it without any exit condition.
🌐
Sololearn
sololearn.com › en › Discuss › 2040855 › any-other-ways-for-creating-infinite-loop-using-java
ANY OTHER WAYS FOR CREATING INFINITE LOOP USING JAVA? | Sololearn: Learn to code for FREE!
October 18, 2019 - What Seb TheS said, infinite recursion simulates an infinite loop but isn't exactly the same. And it is possible in Java. while (true){ //code } for(int i = 1;i!=0;i++){ //code } do{ //code }while(true);