Puzzle 26: in a loop

Source: Internet
Author: User

The following program calculates the number of iterations of a loop and prints out the Count value at the end of the loop. So what does it print?

public class InTheLoop {    public static final int END = Integer.MAX_VALUE;    public static final int START = END - 100;    public static void main(String[] args) {        int count = 0;        for (int i = START; i <= END; i++)            count++;        System.out.println(count);    }}

If you do not view this program very carefully, you may think it will print 100 because end is 100 larger than start. If you are a little more careful, you may find that the program does not use typical loop usage. Most cycles run continuously when the cyclic index is smaller than the terminated value, and this loop runs continuously when the cyclic index is smaller than or equal to the terminated value. So it will print 101, right?

Well, it's not. If you run the program, you will find that it has nothing to print at all. Worse, it continues until you undo it. It never has the chance to print count, because it inserts an infinite loop before printing its statement.

The problem is that this loop will continue to run when the index (I) is less than or equal to integer. max_value, but all int variables are less than or equal to integer. max_value. Because it is defined as the maximum value among all int values. When I reaches integer. max_value and is re-executed for incremental operations, it bypasses integer. min_value.

If the loop you need iterates near the boundary of the int value, you 'd better use a long variable as the loop index. You only need to change the type of the cyclic index from int to long to solve this problem, so that the program prints the expected 101:

for (long i = START; i <= END; i++)

In general, the lesson here is that int cannot represent all integers. Whenever you use an integer type, you must be aware of its boundary conditions. What if the value overflows or overflows? Therefore, it is usually better to use a type with a larger range. (Integer types include byte, Char, short, Int, and long .)

This problem can also be solved without using the long-type cyclic index variable, but it does not look so beautiful:

int i = START;do {    count++;}while (i++ != END);

If clarity and conciseness occupy an extremely important position, then using a long type of loop index is almost always the best solution.

But there is one exception: If you iterate on all (or almost all) int values, the speed of using the int type of cyclic index can be roughly doubled. The following is the usage of F function on all 4 billion int values:

//Apply the function f to all four billion int valuesint i = Integer.MIN_VALUE;do {    f(i);}while (i++ != Integer.MAX_VALUE);

This puzzle has the same lesson for Language designers as puzzle 3: it may be worth considering and should be supported for arithmetic operations that do not throw exceptions when overflow occurs. At the same time, it may be worth considering that we should make a special design for those loops that are iterative in the range of integer values, just as many other languages do.

Puzzle 26: in a loop

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.