FizzBuzz in Java

Description: Print the numbers from 1 to 15. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for multiples of both print FizzBuzz.

Hint:

  • Check the multiples of 15 (both) first.

Solution

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

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

How it works

  • If you check 3 first, then 15 would print only Fizz. So the most special case must come first.

Read Java for Loop.


Learn more about the similar topics:
Tutorials
Java if, else and else if
Java switch Statement and Expression
Java for Loop
Java while and do while Loop
Java break and continue
Exercises & Assignments
Find the largest of three numbers
Check if a year is a leap year
FizzBuzz in Java
Sum of the digits of a number
Print a multiplication table
Check if a number is prime
Interview Questions & Answers
No Content Found.