Java Programming Tutorials

Java programming tutorials with many code examples!

Fizz Buzz in Java

Problem:

How to write Fizz Buzz in Java?

The problem is as follows:

Write a program that prints the numbers from 1 to 100. But for multiples of three print ‘Fizz’ instead of the number and for the multiples of five print ‘Buzz’. For numbers which are multiples of both three and five print ‘FizzBuzz’.

It’s a very common task on job interviews.

Solution:

It can be implemented in a few different ways. Here are sample two solutions:

  1. The simplest solution: fizzBuzz1()
  2. Interesting solution without if-else constructs!
package com.farenda.solved;

public class JavaSolved {

    private static String[] OUTPUTS = {
        "FizzBuzz", "%d", "%d", "Fizz", "%d", "Buzz", "%d",
        "%d", "%d", "Fizz", "Buzz", "%d", "Fizz", "%d", "%d"
    };

    public static void main(String[] args) {
        fizzBuzz1();
        fizzBuzz2();
    }

    private static void fizzBuzz1() {
        for (int i = 1; i <= 100; ++i) {
            if (i % 15 == 0) {
                System.out.println("FizzBuzz");
            } else if (i % 3 == 0) {
                System.out.println("Fizz");
            } else if (i % 5 == 0) {
                System.out.println("Buzz");
            } else {
                System.out.println(i);
            }
        }
    }

    private static void fizzBuzz2() {
        for (int i = 1; i <= 100; ++i) {
            System.out.printf(OUTPUTS[i % 15] + "%n", i);
        }
    }
}

Result:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
... // rest of the output you can imagine
Share with the World!