Saturday, May 21, 2022

2 Ways to solve FizzBuzz in Java? [Example]

Hello guys, if you are learning to code or preparing for interviews and looking how to solve the FizzBuzz problem in Java then you have come to the right place. Earlier, I have shared 75 programming exercises and in this article, I will teach you how to solve the FizzBuzz problem in Java. FizzBuzz is one of the most frequently asked questions on programming interviews and used to filter candidates on Coding interviews who can't code. It looks extremely simple but it's tricky for those programmers or coders who struggle to structure their code or lack the ability to convert a simple algorithm into code. 

At the same time, it's also a good programming exercise for beginners who wants to learn to code and develop a coding sense. In fact, these are the first few programs I teach my coding class students.  

Fizzbuzz problem statement is very simple, you need to write a program that returns "fizz" if the number is a multiplier of 3, return "buzz" if its multiplier of 5, and return "fizzbuzz" if the number is divisible by both 3 and 5. 

If the number is not divisible by either 3 or 5 then it should just return the number itself. You can see nothing is fancy when it comes to thinking about the solution, but when you start coding, you will see a problem with structuring your code, particularly if-else blocks.

In this article, we will go through a couple of solutions to understand the crux of this problem. If you are learning Java 8, then you can also solve this problem using lambda expressions and streams, as shown here.

Btw, if you are new to the Java Programming world and not familiar with basic Java operators and concepts like remainder operator, equality operator, and how to code a function and program in Java then I highly recommend you to join a comprehensive Java course. If you need a recommendation, I suggest checking out The Complete Java Masterclass on Udemy. This 8--hour course is the most comprehensive yet affordable course. 




FizzBuzz Solution in Java - 1

Many programmers come up with the following solution when first faced with the Fizzbuzz problem :
 public static String fizzBuzz(int number) {
        if (number % 3 == 0) {
            if (number % 5 == 0) {
                return "fizzbuzz";
            } else {
                return "fizz";
            }
        } else if (number % 5 == 0) {
            return "buzz";
        }
        return String.valueOf(number);
    }

If you look at this solution closely you will find that the structure of the if statements are not good, and there are two tests for the same condition i.e. two if block to check if the number is divisible by 5. 

The problem is the code is not good but you should give the benefit of the doubt to the programmer because even though a test of 5 is written twice they are in different branches, and only one of them will execute, but I agree the code is not clean.

Btw, if you are keen to learn more about solving coding problems and want to solve more coding problems then I suggest you take a look at a course like LeetCode in Java: Algorithms Coding Interview Questions, which teaches you how to solve coding problems from LeetCode, one of the popular coding problem websites. 



FizzBuzz Solution in Java - II

The key to coming with a perfect solution is coming up with an approach to do the test for divisible by both 3 and 5 first. This brings more readability without duplication, as shown here
public static String fizzBuzz2(int number) {

        if (number % 15 == 0) {
            return "fizzbuzz";
        } else if (number % 5 == 0) {
            return "buzz";
        } else if (number % 3 == 0) {
            return "fizz";
        }
        return String.valueOf(number);
 }

You can see that it's much cleaner even though it is also doing the test twice, but it's more pleasing to the eye and straightforward. 

Btw, If you are preparing for programming job interviews and looking for some coding problems to prepare well, then I will recommend you to go through problems given in the book, Cracking the Coding Interview by Gayle Mcdowell. It contains around 150 programming questions and their solutions with a good explanation.

How to solve FizzBuzz in Java with example




Java Program to solve FizzBuzz Problem for Beginners - example

Here is our complete Java program which combines both approaches to solving the fizz buzz problem. We also have some unit tests to verify our solution meets the problem statements.
import org.junit.Test;
import static org.junit.Assert.*;
/**
 * Java Program to solve FizzBuzz problem
 * 
 * @author WINDOWS 10
 *
 */
public class FizzBuzzTest {

    /**
     * Java Method to solve FizzBuzz problem, which states that program
     * should print fizz if number is multiple of 3, 
     * print buzz if number is multiple
     * of 5, and print fizzbuzz if number is multiple of both 3 and 5
     * 
     * @param number
     * @return
     */
    public static String fizzBuzz(int number) {

        if (number % 3 == 0) {
            if (number % 5 == 0) {
                return "fizzbuzz";
            } else {
                return "fizz";
            }
        } else if (number % 5 == 0) {
            return "buzz";
        }
        return String.valueOf(number);
    }

    /**
     * An improved version of earlier solution, much cleaner than previous
     * version because we have tested for divisible by 3 and 5 first.
     * It avoid duplication also.
     */
    public static String fizzBuzz2(int number) {
        if (number % 15 == 0) {
            return "fizzbuzz";
        } else if (number % 5 == 0) {
            return "buzz";
        } else if (number % 3 == 0) {
            return "fizz";
        }
        return String.valueOf(number);
    }
    
    
    @Test
    public void testFizzBuzz(){
        assertEquals("fizz", fizzBuzz(3));
        assertEquals("buzz", fizzBuzz(5));
        assertEquals("fizzbuzz", fizzBuzz(15));
        assertEquals("2", fizzBuzz(2));
    }
    
    @Test
    public void testFizzBuzzV2(){
        assertEquals("fizz", fizzBuzzV2(3));
        assertEquals("buzz", fizzBuzzV2(5));
        assertEquals("fizzbuzz", fizzBuzzV2(15));
        assertEquals("2", fizzBuzzV2(2));
    }
}

Test Result :
All Pass

That's all about how to solve FizzBuzz Problem in Java.  Sometimes FizzBuzz is also asked as following problem statement, write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers that are multiples of both three and five print “FizzBuzz". So don't confuse there, the same logic works fine.



Other Coding Problems for Practice 
If you are a computer science graduate and serious about doing well on coding based questions on programming job interviews, try to solve the following problems:
  • How to check if a given number is prime or not? (solution)
  • Write a program to print the highest frequency word from a text file? (solution)
  • How to find if given String is a palindrome in Java? (solution)
  • How to calculate factorial using recursion and iteration? (solution)
  • How to reverse an integer variable in Java? (solution)
  • Write code to implement Bubble sort algorithm in Java? (code)
  • How do you reverse the word of a sentence in Java? (solution)
  • How to find the highest and lowest number from the integer array? (answer)
  • How do you swap two integers without using a temporary variable? (solution)
  • Top 10 Programming problems from Java Interviews? (article)
  • Write a program to check if a number is the power of two or not? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • How to reverse String in Java without using StringBuffer? (solution)
  • Write code to implement Quicksort algorithm in Java? (algorithm)
  • How to find a missing number in a sorted array? (solution)
  • Write a program to code insertion sort algorithm in Java (program)

Thanks for reading this article so far. If you like this coding problem and solution then please share it with your friends and colleagues. If you have any doubt then please drop a note.

P. S. - If you are a beginner and looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.

10 comments:

  1. Another possible solution is:

    public static String fizzBuzz3(int number) {
    StringBuilder sb = new StringBuilder();
    if (number % 3 == 0) {
    sb.append("fizz");
    }
    if (number % 5 == 0) {
    sb.append("buzz");
    }

    return sb.length() == 0 ? String.valueOf(number) : sb.toString();
    }

    BTW, you have compile error in testFizzBuzzV2 method.

    ReplyDelete
  2. Here is how to solve FizzBuzz in Java 8 using lambda expression and method references, awesome!!.

    ReplyDelete
  3. Not sure how all tests can pass when you're calling a function that doesn't exist (fizzBuzzV2)

    ReplyDelete
  4. santhosh narayanaswamyApril 24, 2018 at 2:58 AM

    for (i=30;i<100;i++){
    console.log(i + ((i%3)==0?"fizz":"") + ((i%5)==0?"buzz":""));
    }

    ReplyDelete
  5. Ok, I'm not even sure what I did. I tried the code in the example and it doesn't do jack. Maybe my code is wrong, I'm trying to understand it and write it without using a string declaration. How wrong is this code and can someone offer some guidance?

    var number = 0;
    var ThisIsIt =true;


    while(ThisIsIt) {

    if (number % 3 == 0) {
    ThisIsIt= true;
    document.write("fizz");
    }
    else if(number % 5 == 0) {
    ThisIsIt = true;
    document.write("buzz");

    }
    else if((number % 5 == 0) && (number % 3 == 0){
    ThisIsIt = true;
    document.write("fizzbuzz");
    }
    else if{
    ThisIsIt= true;
    document.write(number);
    }
    else(number<=101){
    ThisIsIt = false;
    break;

    }

    ReplyDelete
  6. List strRet = new ArrayList();

    for (int i=1; i<=n; i++)
    {
    if (i%15==0)
    strRet.add("FizzBuzz");

    // number divisible by 5, print 'Buzz'
    // in place of the number
    else if (i%5==0)
    strRet.add("Buzz");

    // number divisible by 3, print 'Fizz'
    // in place of the number
    else if (i%3==0)
    strRet.add("Fizz");

    // number divisible by 15(divisible by
    // both 3 & 5), print 'FizzBuzz' in
    // place of the number

    else // print the numbers
    strRet.add(Integer.toString(i));
    }

    return strRet;

    ReplyDelete
  7. private static void fizzBuzz() {
    for (int i = 1; i <= 100; i++) {
    System.out.print((i % 15 == 0) ? "fizzbuzz " : ((i % 3 == 0) ? "fizz " : ((i % 5 == 0) ? "buzz " : i + " ")));
    }
    }

    ReplyDelete
  8. how do you create the fizzbuzz code but have a user input on the divisors

    ReplyDelete
    Replies
    1. You can use Scanner to accept user input in Java. You can see this tutorial to learn how to accept user input form console, I have shared both code and explanation there.

      Delete

Feel free to comment, ask questions if you have any doubt.