FizzBuzz Program in Java [2 ways]

In this post, we will be learning about the FizzBuzz program in Java. This question is perfect for filtering out candidates who lacks programming ability. FizzBuzz is a fun game.

In the below post I will be sharing two solutions :

1. Simple FizzBuzz Program before Java 8
2. Using Java 8

The rules of the FizzBuzz game are given below:

1. If a given number is divisible by 3 then the java program should print "Fizz".
2. If a given number is divisible by 5 then the java program should print "Buzz".
3. If a given number is divisible by both 3 and 5 then the java program should print "FizzBuzz".
4. Otherwise print the given number as it is.

FizzBuzz Program Example

If we need to print the FizzBuzz program for the first 30 numbers starting from 1, then the Output must be like below:

1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz

1. Simple FizzBuzz Program [Before Java 8]

Below is the simple java program for FizzBuzz:

import java.util.*;
public class FizzBuzz {
    public static void main(String args[]) {
      System.out.println("Enter any valid number : ");    
      Scanner in = new Scanner(System.in);
      Integer input = in.nextInt();
      
      for(int i=1 ; i <= input ; i++)
      {        
        if(i % 3 == 0 && i % 5 == 0)// Check multiple of 3 and 5  
            System.out.print("FizzBuzz");
        else if (i % 3 == 0)// Check multiple of 3
            System.out.print("Fizz");
        else if (i % 5 == 0)// Check multiple of 5  
            System.out.print("Buzz");
        else
            System.out.print(i);// Not a multiple of 3 and 5  
        System.out.print(" ");    
      } 
    }
}

Output: 
FizzBuzz Program in Java

2. Java 8 Solution for FizzBuzz

Below is the Java 8 solution for FizzBuzz:  

import java.util.*;
import java.util.stream.*;
public class FizzBuzz {
    public static void main(String args[]) {
      System.out.print("Enter any valid number : ");    
      Scanner in = new Scanner(System.in);
      Integer input = in.nextInt();
      
      IntStream.rangeClosed(1,input)
               .mapToObj(i -> i%3 == 0 ? (i%5 == 0 ? "FizzBuzz" : "Fizz") : (i%5 == 0 ? "Buzz" : i))
               .forEach(System.out::println);
      
      in.close();
    }
}

Output:

Fizz Buzz Java 8 Solution











That's all for today. Please mention in comments in case you know any other way to solve FizzBuzz Program in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry