The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

A Fractal Mickey Mouse

If you write recursive graphical methods, you often get interesting shapes called fractals. For example, to draw a fractal Mickey Mouse, we can modify draw so that it calls itself recursively:

  public static void draw
               (Graphics g, int x, int y, int width, int height) {
    if (height == 0) return;

    g.drawOval (x, y, width, height);
    draw (g, x, y, width/2, height/2);
    draw (g, x+width/2, y, width/2, height/2);

Only a couple of changes are required. First, instead of invoking drawOval to draw the ears, we invoke draw to draw recursive ears; that is, ears that have ears that have ears of their own, and so on. Also, instead of invoking drawOval on the Graphics object g, we just invoke draw and pass g as an argument.

Finally, and most importantly, notice that I added a line at the beginning of the method that checks whether the height is equal to zero, and if it is, it returns immediately without drawing any circles, and without making any recursive calls. This is necessary because otherwise we would just draw smaller and smaller circles and the program would never terminate. This is known as infinite recursion, and it is generally not considered a good idea.

Actually, in Java an infinite recursion will eventually cause a StackOverflowException. If you ever get this error, you will know why.

The output of this program looks like this:

That might not seem too exciting yet, but with only a few modifications, you can get this:

Can you figure out how?

Last Update: 2011-01-24