While looking up common programming interview questions, I realized that I’d never actually solved FizzBuzz.

I’d heard of FizzBuzz before and had thought through solving it but I’d never actually tried to solve it. It just seems so simple right? If you’re unfamiliar with FizzBuzz, the prompt is at the top of each code snippet below:

First, here’s FizzBuzz in multiple lines:

/*  Write a short program that prints each number from 1 to 100 on a new line.
    For each multiple of 3, print "Fizz" instead of the number.
    For each multiple of 5, print "Buzz" instead of the number.
    For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
*/
public class FizzBuzz {

    public static void main(String[] args) {
        for(int i=1; i<=100; i++) {
            String num = i+"";
            if (i%3 == 0 && i%5 == 0) {
                num = "FizzBuzz";
            }
            else if (i%3== 0) {
                num = "Fizz";
            }
            else if (i%5 == 0) {
                num = "Buzz";
            }
            System.out.println(num);
        }
    }

}

And here’s FizzBuzz in one line:

/*  Write a short program that prints each number from 1 to 100 on a new line.
    For each multiple of 3, print "Fizz" instead of the number.
    For each multiple of 5, print "Buzz" instead of the number.
    For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
*/
public class FizzBuzz {
    public static void main(String[] args) {
        for(int i=1; i<=100; i++) {
            /*Solution uses the conditional or ternary operator to make decisions instead of if statements.
              It's essentially one big assignment inside of a print statement. Whatever the return become is
              what's printed to the console.

               Logically it reads like this:
               if "i" is divisible by 3 and 5 return "FizzBuzz"
               else if "i" is divisible by 3 return "Fizz"
               else if "i" is divisible by 5 return "Buzz"
               else return int value of "i" with an empty string appended to cast to String */
            System.out.println(i%3==0 && i%5==0 ? "FizzBuzz" : i%3==0 ? "Fizz": i%5==0 ? "Buzz" : i+"");
        }
    }
}

To give you an idea of what you’re looking at, first, I solved it in the most obvious way possible. I then proceeded to simplify it repeatedly until I realized I could solve it in one line. Once I realized I could solve it in one line, I then tried to see what Java idioms I could throw in. I ended up throwing in some conditional/ternary operators to replace the “IF” statements.

Tested the output, added some comments and BOOM! FizzBuzz.

//Note: Never do this, while it looks cool, it's a mess and future programmers will hate you.