Example of a For statement in Java that causes an infinite dead loop _java

Source: Internet
Author: User

A For loop is commonly used in Java development, which is very helpful for simplifying business processing and improving efficiency. But to prevent the program algorithm can lead to a dead loop of the situation, and some of the dead loop is not easy to detect. For example, the algorithm is extremely easy to think of as 50, which is actually a dead loop of infinity.

public class Cyctest { 
  /** 
   * @param args the command line arguments 
  /public static void Main (string[) AR GS) { 
    int end = Integer.max_value;//define the number of cyclic terminations, which can be infinitely large, different from the int type. 
    int start = end-50;     Define starting value 
    int count = 0;        Initial value for 
    (int i=start;i<=end;i++) {//Loop body 
      count++;         Cyclic counting 
    System.out.println ("The number of cycles is:" +count); Output 
  } 
  }  

Output results:

Run: 
the number of times to cycle: 1 
The number of cycles: 2 
The number of cycles: 3 
... The number of times this cycle is: 51 The number of times this cycle: 
 

Summarize:
Some people think that the output will be 50 times, which is actually a dead loop. The end is infinitely large, and the i<=end is an infinitely large number. So there is no limit to that. for (int i=start,i<end;i++), the result is 50. I<end, which means that the boundary value cannot be an infinite approximation, and from start to end it becomes a range, and the interval is 50. Therefore, considering the range of data types in development, especially the judgment of conditions and the value of boundary.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.