×

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

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Star Program in Java

By solving the patterns, we can develop our coding skills and logical thinking. Mostly each pattern program uses two or more loops. Loops' number depends on the complexity of logic....

3 minutes read.

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws...

3 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Java Externalization

What is Externalization in Java? Externalization is a concept that is advanced to serialization. Serialization is a concept where we can transfer an object from our JVM ( Java virtual machine...

3 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes 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.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.