What is Fizz buzz game?
- FizzBuzz game is very famous interview question.
- Fizz buzz is a group word game used to teach division.
- Players generally sit in a circle. The player designated to go first says the number “1”, and each player thenceforth counts one number in turn.
- However, any number divisible by 3 is replaced by the word fizz and any divisible by 5 by the word buzz. Numbers divisible by 15 become fizzbuzz. A player who hesitates or makes a mistake is eliminated from the game.
- Print special string if any number is divisible for 3, 5 & 15.
- If number is divisible by 3 ( number % 3 == 0 ), then we will print “Fizz”.
- If number is divisible by 5 ( number % 5 == 0), then we will print “Buzz”.
- If number is divisible by 5 & 3 i.e. 15 ( number % 15 == 0 ), then we will print “FizzBuzz”.

Approach 1: Using Java Stream
Implement FizzBuzz game using Java Stream
import java.util.function.IntPredicate; import java.util.stream.Collectors; import java.util.stream.IntStream; public class FizzBuzz { public static void main(String[] args) { final int LIMIT = 15 ; IntPredicate isDivisibleBy3 = i -> i % 3 == 0 ; IntPredicate isDivisibleBy5 = i -> i % 5 == 0 ; String result = IntStream.rangeClosed( 1 , LIMIT) .mapToObj(i -> { String output = "" ; if (isDivisibleBy3.test(i)) output += "Fizz" ; if (isDivisibleBy5.test(i)) output += "Buzz" ; return output.isEmpty() ? String.valueOf(i) : output; }) .collect(Collectors.joining( "\n" )); System.out.println(result); } } |
Output: Program to print FizzBuzz game sequence.
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz |
Approach 2: Implement FizzBuzz – Traditional Loop
Program: Create FizzBuzz game in java (example)
package org.learn.fizzbuzz; import java.util.Scanner; public class DemoFizzBuzz { private static final String FIZZ = "Fizz" ; private static final String BUZZ = "Buzz" ; private static final String FIZZ_BUZZ = "FizzBuzz" ; public static void main(String[] args) { try (Scanner scanner = new Scanner(System.in)) { System.out.println( "Enter input number : " ); int inputNumber = scanner.nextInt(); for ( int number = 1 ; number <= inputNumber; number++) { // If number is divisible by 15 ( 5 * 3) if (number % 15 == 0 ) { System.out.printf( "%s " , FIZZ_BUZZ); } else if (number % 3 == 0 ) { // If number is divisible by 3 System.out.printf( "%s " , FIZZ); } else if (number % 5 == 0 ) { // If number is divisible by 5 System.out.printf( "%s " , BUZZ); } else { System.out.printf( "%d " , number); } } } } } |
Output: implement FizzBuzz game program in java:
Enter input number : 10 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz Enter input number : 18 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz |