×

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

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.