O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

FizzBuzz

FizzBuzz is a game I learned long ago in elementary-school French class, as a way to practice counting in that language. The players take turns counting, starting with one and going up. The rules are simple: when your turn arrives, you say the next number. However, if that number is a multiple of five, you should say the word "fizz" (preferably with a French accent) instead. If the number is a multiple of seven, you should say "buzz." And if it is a multiple of both, you should say "fizzbuzz." If you mess up, you're out, and the game continues without you.

Example 1-2 is a Java program named FizzBuzz that plays a version of the game. Actually, it isn't a very interesting version of the game because the computer plays by itself, and it doesn't count in French! What is interesting to us is the Java code that goes into this example. It demonstrates the use of a for loop to count from 1 to 100 and the use of if/else statements to decide whether to output the number or one of the words "fizz", "buzz", or "fizzbuzz". (In this case, the if/else statement is used as an if/elseif/elseif/else statement, as we'll discuss shortly.)

This program introduces System.out.print( ). This method is just like System.out.println( ), except that it doesn't terminate the line of output. Whatever is output next appears on the same line.

The example also shows another style for comments. Anything, on any number of lines, between the characters /* and the characters */ is a comment in Java and ignored by the compiler. When one of these comments begins with /**, as the one in this example does, then it is additionally a doc comment, which means its contents are used by the javadoc program that automatically generates API documentation from Java source code.

Example 1-2. FizzBuzz.java

package je3.basics;

/**
 * This program plays the game "Fizzbuzz".  It counts to 100, replacing each
 * multiple of 5 with the word "fizz", each multiple of 7 with the word "buzz",
 * and each multiple of both with the word "fizzbuzz".  It uses the modulo
 * operator (%) to determine if a number is divisible by another.
 **/
public class FizzBuzz {                      // Everything in Java is a class
    public static void main(String[  ] args) { // Every program must have main( )
        for(int i = 1; i <= 100; i++) {           // count from 1 to 100
            if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
                System.out.print("fizzbuzz");   
            else if ((i % 5) == 0)                // Is it a multiple of 5?
                System.out.print("fizz"); 
            else if ((i % 7) == 0)                // Is it a multiple of 7?
                System.out.print("buzz"); 
            else System.out.print(i);             // Not a multiple of 5 or 7
            System.out.print(" ");                
        }
        System.out.println( );
    }
}

The for and if/else statements may require a bit of explanation for programmers who have not encountered them before. A for statement sets up a loop, so that some code can be executed multiple times. The for keyword is followed by three Java expressions that specify the parameters of the loop. The syntax is:

for(initialize ; test ; update)
    body
            

The initialize expression does any necessary initialization. It is run once, before the loop starts. Usually, it sets an initial value for a loop counter variable. Often, as in this example, the loop counter is used only within the loop, so the initialize expression also declares the variable.

The test expression checks whether the loop should continue. It is evaluated before each execution of the loop body. If it evaluates to true, the loop is executed. When it evaluates to false, however, the loop body is not executed, and the loop terminates.

The update expression is evaluated at the end of each iteration of the loop; it does anything necessary to set up the loop for the next iteration. Usually, it simply increments or decrements the loop counter variable.

Finally, the body is the Java code that is run each time through the loop. It can be a single Java statement or a whole block of Java code, enclosed by curly braces.

This explanation should make it clear that the for loop in Example 1-2 counts from 1 to 100.

The if/else statement is simpler than the for statement. Its syntax is:

if (expression)
    statement1
else
    statement2
            

When Java encounters an if statement, it evaluates the specified expression. If the expression evaluates to true, statement1 is executed. Otherwise, statement2 is evaluated. That is all if/else does; there is no looping involved, so the program continues with the next statement following if/else. The else clause and statement2 that follows it are entirely optional. If they are omitted, and the expression evaluates to false, the if statement does nothing. The statements following the if and else clauses can be either single Java statements or entire blocks of Java code, contained within curly braces.

The thing to note about the if/else statement (and the for statement, for that matter) is that it can contain other statements, including other if/else statements. This is how the statement was used in Example 1-2, where we saw what looked like an if/elseif/elseif/else statement. In fact, this is simply an if/else statement within an if/else statement within an if/else statement. This structure becomes clearer if the code is rewritten to use curly braces:

if (((i % 5) == 0)&& ((i % 7) == 0))
    System.out.print("fizzbuzz");    
else {
    if ((i % 5) == 0) 
        System.out.print("fizz"); 
    else {
        if ((i % 7) == 0) 
            System.out.print("buzz");
        else 
            System.out.print(i);                  
    }
}

Note, however, that this sort of nested if/else logic is not typically written out with a full set of curly braces in this way. The else if programming construct is a commonly used idiom that you will quickly become accustomed to. You may have also noticed that I use a compact coding style that keeps everything on a single line wherever possible. Thus, you'll often see:

if (expression) statement
            

I do this so that the code remains compact and manageable, and therefore easier to study in the printed form in which it appears here. You may prefer to use a more highly structured, less compact style in your own code.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required