Open In App

Infinite Loop Puzzles in Java

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, Infinite loops are a very important concept to understand. Infinite loops can occur due to various reasons such as overflows, unboxing and logic comparisons. In this article, we will understand two common puzzles related to infinite loop.

Problem 1: Infinite Loop Using Integer Overflow

In Java, the int data type can store numbers from -2,147,483,648 to 2,147,483,647 which is represented by Integer.MIN_VALUE and Integer.MAX_VALUE. What is going to happen when we exceed these ranges? and this is where integer overflow comes into play and it can lead to an infinite loop if used in a loop condition.

Example:

Java
// Demonstrating infinite loop 
// due to integer overflow

class Geeks {
    public static void main(String args[]) {
        // Start one less than the maximum value of int
        int s = Integer.MAX_VALUE - 1; 
        for (int i = s; i <= s + 1; i++) {
            // Infinite loop
        }
    }
}


Explanation: Here, in the above example, we have declared a variable s, one less than the maximum value that an int can hold which is Integer.MAX_VALUE-1. The loop starts from i=start which is 2,147,483,645 and we know s is close to the maximum int value and when the loop increases i, it reaches Integer.MAX_VALUE and the next increment causes overflow and wrap around to Integer.MIN_VALUE. 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.


Problem 2: Infinite Loop Using Autoboxing and Identity Comparison

Java can aslo work with primitive types and objects. But when we work with objects like Intege, we may come into a situation where the comparison logic leads to unexpected results.

Example:

Java
// Demonstrating infinite loop

class Geeks {
    public static void main(String s[]) {
        // Integer object with value 0
        Integer i = new Integer(0); 
        // Another Integer object with value 0
        Integer j = new Integer(0); 

        while (i <= j && j <= i && i != j) {
            // Infinite loop
        }
    }
}

Explanation: In the above example, i and j are two Integer objects. Java automatically converts primitive int values into Integer objects, this is known as autoboxing. In the while loop, the expressions i <= j and j <= i cause Java to unbox the Integer objects back to primitive int values for numerical comparison, which evaluates to true since both have the same value 0.

The condition i != j compares the object references, not the values. Since i and j are created using new Integer(0), they are different objects in memory, so i != j evaluates to true. As a result, all three conditions in the while loop evaluate to true and the loop to run infinitely.


Article Tags :
Practice Tags :

Similar Reads