FizzBuzz Program in Java

1. What is FizzBuzz?

FizzBuzz is a fun game mostly played in elementary school. The rules are simple:

When our turn arrives, we say the next number (preferably with a French accent). However:

  • If that number is a multiple of five, we say the word “fizz“.
  • If the number is a multiple of seven, we say “buzz“.
  • If it is a multiple of both, we say “fizzbuzz.”

If we mess up, we are out, and the game continues without us.

Please note that different divisors can be used in place of, or in addition to, 5 and 7, and different words or gestures can replace “fizz” or “buzz”. [Ref]

Let’s learn to write a program to simulate this game in Java.

2. FizzBuzz Program using Java Streams

Let’s design a solution using Java 8 Stream API. The following program uses IntStream class which is used to generate a Stream of integers in a range.

We use the ternary operator to check each generated number n in sequence, and check if number is divisible by 7 or 5.

int end = 100;

IntStream.rangeClosed(1, end)
        .mapToObj(
                i -> i % 5 == 0 ? 
                        (i % 7 == 0 ? "FizzBuzz" : "Fizz") : 
                        (i % 7 == 0 ? "Buzz" : i))
        .forEach(System.out::println);

Program Output:

1
2
3
4
Fizz
6
Buzz
...
...
34
FizzBuzz
...
...

3. FizzBuzz Program using For-Loop

If you are still not using Java 8, or you are asked to write the program using loops, then use the following program which replaces the stream with a loop, and ternary operator with if-else statements.

int end = 100;

for (int i = 1; i <= end; i++) {

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

The program output is similar to the previous solution.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode