Apr 29 2011

Can You Spot the Infinite Loop?

Can you spot the infinite loop in the following snippet of code?

int i = 0;
{
    i++;
}while(i < 5);

The above code caused a critical bug in a application I was working on. At first sight, the code looks okay, especially since it compiles. It’s a do-while loop with a condition that seems that it would break when the variable i is equals or greater than 5. The variable i is set and incremented correctly but unfortunately this causes an infinite do nothing loop. Did you spot the problem? An important keyword is missing from the do-while loop, the do. Let me add comments to explain each statement as the compiler sees it…

// Initialize the variable i
int i = 0;

// Create a block and increment i by one
{
    i++;
}

// Infinite loop with an empty code block
while(i < 5);

The problem is that the while loop can have zero or one code block of statements (where a single statement can be a code block). If the state of what you are testing in the condition does not change because of the test, or because of the statement you are looping over, then you have an infinite loop. In the above code, because of a badly written do-while loop, this loop does not have statements that update the variables in the condition and so this while loop never breaks out.

The correct code would be the following…

int i = 0;
do {
    i++;
}while(i < 5);

Apr 27 2011

How To Print The Alphabet in Java?

In Java, the primitive value of type char can be converted to the primitive int. An an integer within the range of a character can be converted to a char. For example, the ASCII character code for the character A is 65, for B is 66, etc. Because of a char value can be interchanged with the integer value that represents its character code I can create a loop that starts from the letter A and stops at the character Z and I increment one character at a time. Here is the code snippet to print each letter of the alphabet in a loop.

for(char c = 'A'; c <= 'Z'; c++) {
    System.out.print(c);
}