×

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will teach you how to create a Java FizzBuzz application. FizzBuzz is quite easy to use. To put it into practise, you must first grasp two ideas. The first prerequisite is a fundamental understanding of coding at the level of any beginner course. Yes, it's that simple.

The most well-known and often used solution to this problem is to employ conditional statements. For each number in n, we must determine if it is divisible by four or three. If the number is divided by three, it prints Fizz; if it is divisible by four, it prints Buzz. Fizz-Buzz is a group language game for kids that teaches division. Players take turns counting progressively, substituting any multiple of three with "fizz" and any multiple of five with "buzz".

FizzBuzz is a simple programming challenge used in software developer job interviews to assess whether an applicant can really create code. Imran Ghory invented it, and Jeff Atwood popularised it. The following is a work description: Create a programme that prints the digits 1 through 100.

The FizzBuzz Game Rules

The FizzBuzz game has relatively simple rules:

  • If the number is divisible by three, say Fizz.
  • Say Buzz if the number is divisible by 5.
  • Say FizzBuzz if the number is divisible by both 3 and 5.
  • If the integer is not divisible by three or five, return it.

In Java, there are two approaches to develop a FizzBuzz program:

  • The else-if Statement
  • Java 8 is being used.

Using the else-if conditional statement:

In the following programme, we read from the user an integer (n) that represents the upper limit for printing the Fizz, Buzz, or FizzBuzz. The for loop begins at 1 and continues until the condition i=n turns false. The else-if expression determines whether or not the number is a multiple of 3 and 5.

FizzBuzzExample.java

import java.util.Scanner;  
public class FizzBuzzExample  
{  
public static void main(String args[])   
{  
//scanner class constructor  
Scanner sc = new Scanner(System.in);  
System.out.print("Enter number: ");  
//from the user we read as an integer  
int a = sc.nextInt();  
System.out.println(" Fizz, Buzz, FizzBuzz numbers : ");  
//for loop executes 
//until the condition i<=n becomes false  
for (int i = 1; i <= a; i++)   
{  
//returns true 
if (i%3==0 && i%5==0)   
{   
//if the number is multiple of 3 and 5 print  
System.out.print("FizzBuzz");  
}   
//execution occurs if the condition returns true  
else if (i%3==0)   
{  
// if the number is multiple of 3 print it 
System.out.print("Fizz");  
}   
else if (i%5==0)   
{   
//if the number is multiple of 5 print it
System.out.print("Buzz");  
}   
else   
{  
System.out.print(i);  
}  
//prints space in this case
System.out.print(","+" ");  
}  
//Scanner close  
sc.close();  
}  

Output:

Enter number:15
Fizz, Buzz, FizzBuzz numbers :
1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz

Using Java 8

The IntStream interface is available in Java 8. We used the IntStream interface's following two methods.

The static analysis of the IntStream interface is rangeClosed(). It returns a sequential IntStream for the range supplied.

Syntax:

static IntStream rangeClosed(int startInclusive, int endInclusive) 

The approach takes two parameters into account:

  • startInclusive: This is the first value.
  • endInclusive: The upper inclusive bound.

Using mapToObj():

The technique combines an intermediate action and returns a object-valued Stream contains the list of executing the specified function to the elements of the stream.

Syntax:

<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)

A parameter mapper is parsed by the method (of element type of new stream). It returns the newly created stream.

FizzBuzzExample1:

import java.util.*;  
import java.util.stream.IntStream;  
public class FizzBuzzExample1 
{  
public static void main(String args[])   
{  
Scanner sc = new Scanner(System.in);  
System.out.print("Enter number:");  
//from the user read
int n= sc.nextInt();  
 IntStream.ranC(1, n).maToO(i->i%3==0?(i%5==0? "FizBuz ":"Fiz "):
(i%5==0? "Buzz ": i+" ")).
forEach(System.out::print);  
//Scanner closing  
sc.close();  
}  
}  

Output:

Enter number: 15
1 ,2, Fizz, 4 ,Buzz, Fizz ,7 ,8, Fizz Buzz, 11, Fizz, 13 ,14, FizzBuzz 

By using the ternary operator, the reasoning for FizzBuzz is simplified to one line in the preceding programme. It reduces the size of the line of code. We printed Fizz if the number was a multiple of three, Buzz if it was a multiple of five, and FizzBuzz if it was a multiple of three and five, or else we printed the number itself.


Related Topics

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Matrix Multiplication Program in Java

Matrix Multiplication Program in Java The matrix multiplication program in Java is the continuation of the matrix program in Java that we have already discussed earlier. In this section, we will...

3 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.