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.
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
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.
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.
The method parses two parameters:
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.
The method parses a parameter mapper (of element type of new stream). It returns the new stream.
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