In the loop

Source: Internet
Author: User

[Java] public class InTheLoop {public static final int END = Integer. MAX_VALUE; public static final int BEGIN = END-100; public static void main (String [] args) {int count = 0; for (int I = BEGIN; I <= END; I ++) {count ++;} System. out. println (count) ;}} what will the above Code output? If you do not take a closer look, you may think it is 100. Because the loop is 100 times, but you can see that this loop is not a typical practice, so you think the output should be 101. Actually none. If you do not manually stop the program, it will continue to run. What is the root cause of the problem? The problem is that in the Condition of the for loop, I <= END, that is, I <= Integer. MAX_VALUE. When the loop reaches 100 times, I = Integer. MAX_VALUE, the next cycle I ++, Because I is of the int type, overflow occurs, I = Integer. MIN_VALUE, of course, is smaller than END, so I keeps increasing to Integer. MAX_VALUE, and then overflow into Integer. MIN_VALUE. So the problem is that the int type indicates that the range is too small in this case. You can change the I type from int to long. [Java] www.2cto. compublic class InTheLoop {public static final int END = Integer. MAX_VALUE; public static final int BEGIN = END-100; public static void main (String [] args) {int count = 0; for (long I = BEGIN; I <= END; I ++) {count ++;} System. out. println (count) ;}} in this way, you will soon get the 101 answer. The lesson for Language designers is that it should support arithmetic operations that do not throw exceptions when overflow occurs.

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.