The compiler can easily and unequivocally prove that the first expression always results in an infinite loop, but it's not as easy for the second. In your toy example it's simple, but what if:

  • the variable's contents were read from a file?
  • the variable wasn't local and could be modified by another thread?
  • the variable relied on some user input?

The compiler is clearly not checking for your simpler case because it's forgoing that road altogether. Why? Because it's much harder forbidden by the spec. See section 14.21:

  • http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.21-300-M

(By the way, my compiler does complain when the variable is declared final.)

Answer from Wayne on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › infinite loops in java
Infinite Loops in Java | Baeldung
January 8, 2024 - Simply put, an infinite loop is an instruction sequence that loops endlessly when a terminating condition isn’t met.
🌐
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
Answer: Of course! 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 is reached and some ...
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
Having issues with infinite loops in Java
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 ) More on reddit.com
🌐 r/javahelp
13
0
June 8, 2022
[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
Is there something equivalent to C/Java's for(;;){} infinite for-loop syntax?
Since Kotlin has inline functions, you could create functions that would appear to be language constructs without incurring any overhead and could look like this: loop { println("Poof") } with something like this: inline fun loop(body: () -> Unit): Nothing { while (true) { body() } } More on reddit.com
🌐 r/Kotlin
23
11
July 31, 2022
People also ask

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 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
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
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › infinite loop in java
Mastering Infinite Loop in Java: A Comprehensive Guide with Examples
1 week ago - However, sometimes loops can go awry and create an infinite loop. An infinite loop in Java occurs when a loop's termination condition is not satisfied, causing it to repeat endlessly.
🌐
Scaler
scaler.com › home › topics › infinite loop in java
Infinite Loop in Java - Scaler Topics
July 7, 2024 - In Java, an infinite loop endlessly executes without a stopping condition, potentially causing resource overuse or application crashes. While it can result from programming errors, it might serve intentional purposes based on specific application ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › infinite-loop-puzzles-java
Infinite Loop Puzzles in Java - GeeksforGeeks
May 5, 2025 - The loop will keep on running because the condition i <= s + 1 remains true due to the overflow, which cause an infinite loop. This loop will never end because of the behavior of integer overflow.
Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › avoiding-and-understanding-infinite-loops-in-java-b3a294d11a47
Avoiding and Understanding Infinite Loops in Java
August 26, 2024 - Learn how to identify, debug, and prevent infinite loops in Java. This beginner-friendly guide covers loop basics, common problems, and best practices.
🌐
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 loop will continue to execute indefinitely.
🌐
AlgoCademy
algocademy.com › link
Infinite While Loops in Java | AlgoCademy
In this example, the loop will print the values from 0 to 4. The variable i is incremented in each iteration, ensuring that the loop eventually terminates when i reaches 5. Understanding this basic structure is essential before moving on to more complex aspects, such as preventing infinite loops.
🌐
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.
🌐
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 - yes its basicly different. a state of method call are saved in stack memory, so doing recrusion could fill up the stack. once its full Stackoverflow error will occur. so theoretically, its possible using recrusion as infinite loop.
🌐
Quora
quora.com › How-do-I-code-infinite-loop-in-Java
How to code infinite loop in Java - Quora
Answer (1 of 3): Infinite loop means a loop that never ends. 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 ...
🌐
Codefinity
codefinity.com › courses › v2 › 8204075c-f832-4cb9-88b1-4e24e74ebdcb › 3e046a04-a59c-4fc2-95d5-5d34cff8249b › dff310b3-1f3f-42a2-9690-1ae6fbbacfd8
Learn Infinite Loop | Loops
Java Basics · Start Learning · An infinite loop is a loop that continues executing indefinitely without a condition that would cause it to terminate. This can result in your program becoming unresponsive or consuming excessive system resources.
🌐
PrepBytes
prepbytes.com › home › java › infinite loop example in java
Infinite Loop Example in Java
January 31, 2023 - An infinite loop in java is a sequence of instructions that loops indefinitely until the system crashes. In Java, an infinite loop occurs when the loop’s ending condition is not met.
🌐
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.
🌐
javaspring
javaspring.net › blog › infinite-loop-java
Understanding and Working with Infinite Loops in Java — javaspring.net
In Java, loops are a fundamental ... as the name suggests, is a loop that continues to execute indefinitely unless an external factor, such as an exception or a termination signal, interrupts it....
🌐
Opensource.com
opensource.com › article › 23 › 1 › java-loops
A 4-minute guide to Java loops | Opensource.com
January 14, 2023 - In this sample code, count is set ... the end of the first iteration, though: ... An infinite loop, as its name suggests, never ends....
🌐
AlgoCademy
algocademy.com › link
Infinite For Loops in Java | AlgoCademy
An infinite for loop occurs when the terminating condition is never met. This can happen if the condition always evaluates to true or if the loop's increment/decrement logic causes it to reset to its initial state.