An example of a for statement in Java that causes an infinite loop

  • 2020-04-01 03:57:35
  • OfStack

Often used in Java development, the For loop is useful For simplifying business processes and increasing efficiency. But to prevent the algorithm may lead to the situation of dead loop, and some of the dead loop is not easy to detect. For example, in the following example, it is easy for the algorithm to think that 50 is actually an infinite loop.


public class CycTest { 
   
  public static void main(String[] args) { 
    int end = Integer.MAX_VALUE; //Define a loop termination number, which can be infinite, as distinguished from an int.
    int start = end-50;     //Define the starting value
    int count = 0;        //The initial value
    for(int i=start;i<=end;i++){ //The loop body
      count++;         //Cycle count
    System.out.println(" The number of times of this cycle is :"+count); //The output
  } 
  }  
} 

Output results:


run: 
 The number of times of this cycle is :1 
 The number of times of this cycle is :2 
 The number of times of this cycle is :3 
...... 
 The number of times of this cycle is :49 
 The number of times of this cycle is :50 
 The number of times of this cycle is :51 
...... 

Conclusion:
One might think that the output would be 50, but it's actually a dead loop. End is an infinite number. Is equal to end, which is infinity. So it's infinite. For (int I = start, i< The end; I++), which is 50. I< End, it's not going to be an infinite approximation, but it's going to be an interval from start to end, which is 50. Therefore, the value range of various data types is considered in the development, especially when the conditional judgment and boundary value are evaluated.


Related articles: