FizzBuzz game program in Java

FizzBuzz game program in Java

FizzBuzz is a fun game played by school children. Players take turns to count numbers incrementally. The rules are simple: if the number is dividable by 3, you say the word “Fizz“, if the number is divisible by 5, you say the word “Buzz“, if the number is divisible by both 3 and 5, you say the word “FizzBuzz” and if the number is not divisible by either of it, you simply say the particular number (an example series is 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz). A player who hesitates or makes a mistake is eliminated from the game. There can be different variations of the game by using different divisors like 5 & 7, 4 & 6 etc. This is one of the most famous programming interview questions for freshers. In this post we will see Java program for Fizz Buzz game.

Fizz Buzz Java solution without using Java 8 features

This is the simplest way to solve FizzBuzz in Java without using any of Java 8 feature. Here is the program.

Below is a sample output of the above program.

If a number is divisible by both 3 and 5, it means the number is also divisible by 15. So you can simply check if the number is divisible by 15 to know if it is divisible by both 3 and 5.

Fizz Buzz Java solution using Java 8

In this section we will see Java program using streams, lambda expression and method reference features.

Solution:1

In this program we have used Java 8 stream and method reference features. Below is a sample output.

Solution:2

Here we have used stream and lambda expression. Below is a sample output of the program.

Solution:3

Here is another variant of the program using lambda expression and streams concept.

Sample output of the above program.

That’s all about FizzBuzz game program in Java. These kind of coding problems are not only useful for freshers, it will also be helpful for experienced programmers to learn new features in Java. If you have any doubt, post it in the comments section.

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

Required fields are marked *. Your email address will not be published.