Skip to main content

Java Bugs

Recommended Week

Year 1 : Weeks 15 - 16

Originator

Ian Holyer

Task

Here are simplified versions of two programs which were submitted as bug reports, claiming that something was wrong with the Java language.

The first is supposed to print out 100, but it doesn't. So what is wrong?

class Loopy
{
    public static void main(String[] args)
    {
        int count = 0;
        for (int i = 0; i < 100; i++);
        {
            count++;
        }
        System.out.println(count);
    }
}

The second is supposed to sort an array of integers into descending order, but it doesn't sort them at all. What is wrong this time?

import java.util.*;

class Disorder
{
    public static void main(String[] args)
    {
        Integer[] numbers = {3, 1, 4, 1, 5, 9};
        Comparator<Integer> descending = new CompareDescending();
        Arrays.sort(numbers, descending);
        String result = Arrays.toString(numbers);
        System.out.println(result);
    }

    static class CompareDescending implements Comparator<Integer>
    {
        public int compare(Integer i1, Integer i2)
        {
            if (i1 > i2) return -1;
            if (i2 < i1) return 1;
            return 0;
        }
    }
}

Version with answers (available for CS staff only)