FizzBuzz Solution in Java

FizzBuzz is a fun game mostly played in elementary school. 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.

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.

Solve FizzBuzz in Java 8

With latest java version being 8, lets design a solution using java 8 constructs.

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

Solve FizzBuzz before Java 8

If you are still not using java 8, then this fizzbuzz solution uses basic for-loop and iterate over range of numbers and decide what to print.

for (int i = 1; i <= num; i++) 
{
	if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
		System.out.println("fizzbuzz");
	else if ((i % 5) == 0) // Is it a multiple of 5?
		System.out.println("fizz");
	else if ((i % 7) == 0) // Is it a multiple of 7?
		System.out.println("buzz");
	else
		System.out.println(i); // Not a multiple of 5 or 7
}

Complete FizzBuzz Example Code

Both solutions are easy enough and self explanatory. Given below is working example sourcecode for fizzbuzz. Feel free to modify and play with the code.

import java.util.stream.IntStream;

public class FizzBuzz 
{
	public static void main(String[] args) 
	{
		fizzBuzzBeforeJava8(100);
		fizzBuzzInJava8(100);
	}

	private static void fizzBuzzBeforeJava8(int num) 
	{
		for (int i = 1; i <= num; i++) 
		{
			if (((i % 5) == 0) && ((i % 7) == 0)) // Is it a multiple of 5 & 7?
				System.out.println("fizzbuzz");
			else if ((i % 5) == 0) // Is it a multiple of 5?
				System.out.println("fizz");
			else if ((i % 7) == 0) // Is it a multiple of 7?
				System.out.println("buzz");
			else
				System.out.println(i); // Not a multiple of 5 or 7
		}
	}

	private static void fizzBuzzInJava8(int num) {
		IntStream.rangeClosed(1, 100)
				.mapToObj(i -> i % 5 == 0 ? (i % 7 == 0 ? "FizzBuzz" : "Fizz") : (i % 7 == 0 ? "Buzz" : i))
				.forEach(System.out::println);
	}
}

Happy Learning !!

Leave a Reply

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