Javatpoint Logo
Javatpoint Logo

FizzBuzz Program in Java

FizzBuzz is a game that is popular among kids. By playing this, kids learn the division. Now, the FizzBuzz game has become a popular programming question that is frequently asked in Java programming interviews. In this section, we will learn how to create a FizzBuzz program in Java.

Rules of the FizzBuzz Game

The rules of the FizzBuzz game are very simple.

  • Say Fizz if the number is divisible by 3.
  • Say Buzz if the number is divisible by 5.
  • Say FizzBuzz if the number is divisible by both 3 and 5.
  • Return the number itself, if the number is not divisible by 3 and 5.

Note: Instead of 3 and 5, you can use different divisors (like 5 and 7, etc.) and string (Fizz and Buzz) also.

Let's implement the above rules in a Java program.

Java FizzBuzz Program

There are two ways to create FizzBuzz program in Java:

  • Using else-if Statement
  • Using Java 8

Using else-if statement

In the following program, we read an integer (n) from the user that is the upper limit to print the Fizz or Buzz or FizzBuzz. The for loop starts from 1 and executes until the condition i<=n becomes false. The else-if statement to check the number is multiple of 3 and 5 or not.

FizzBuzzExample1.java

Output:

FizzBuzz Program in Java

Using Java 8

Java 8 provides the IntStream interface. We have used the following two methods of the IntStream interface.

rangeClosed() Method: It is the static method of the IntStream interface. It returns a sequential IntStream for the specified range.

Syntax:

The method parses two parameters:

  • startInclusive: It is the initial value.
  • endInclusive: The inclusive upper bound.

Using mapToObj() Method

The method performs an intermediate operation and returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.

Syntax:

The method parses a parameter mapper (of element type of new stream). It returns the new stream.

FizzBuzzExample2.java

Output:

Enter the number: 40
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 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz

Note that, in the above program the logic for FizzBuzz is adjusted into one line by using the ternary operator. It reduces the line of code. We have printed Fizz if the number is multiple of 3, prints Buzz if the number is multiple of 5, prints FizzBuzz if the number is multiple of 3 and 5, else prints the number itself.


Next TopicJava Graph




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA