# Introduction

Since I have completely lost the opportunity to touch Java at work, I thought about how to solve the "Fizz Buzz problem" in various ways using Java.

# What is Fizz Buzz?

Fizz Buzz - Wikipedia

• A word game that takes place during long-distance driving or drinking parties in English-speaking countries.
• The first player reads the number "1".
• Subsequent players will read the next number.
• However, if it is divisible by 3, say "Fizz", if it is divisible by 5, say "Buzz", and if it is divisible by both 3 and 5, say "Fizz Buzz".

# General method using For statement

#### `FizzBuzz.java`

``````
/**
*A common method using a for statement.
* @param end The number to end FizzBuzz.
*/
public static void useForLoop(int end) {
for (int i=1; i<=end; i++) {
if (i%3==0 && i%5==0) {
System.out.println("Fizz Buzz");
} else if (i%3==0) {
System.out.println("Fizz");
} else if (i%5==0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
``````

# Method using For statement + ternary operator

#### `FizzBuzz.java`

``````
/**
*A method that utilizes the ternary operator.
* @param end The number to end FizzBuzz.
*/
public static void useForLoopWithTertiaryOperator(int end) {
for (int i=1; i<=end; i++) {
System.out.println(
(i%3==0 && i%5==0) ? "Fizz Buzz" : (i%3==0) ? "Fizz" : (i%5==0) ? "Buzz" : i
);
}
}
``````

# Method using Stream API

#### `FizzBuzz.java`

``````
import java.util.stream.IntStream;
...

/**
*A method that utilizes the Stream API.
* @param end The number to end FizzBuzz.
*/
public static void useStreamAPI(int end) {
IntStream.rangeClosed(1, end)
.mapToObj(i -> (i%3==0 && i%5==0) ? "Fizz Buzz" : (i%3==0) ? "Fizz" : (i%5==0) ? "Buzz" : i)
.forEach(msg -> System.out.println(msg));
}
``````

# Summary

• The oldest way of writing, "general method using For sentence", is the easiest to see and understand.
• The difficulty is that if you repeat the ternary operator, it will be hard to see.
• In the Java Silver SE 8 exam, I had a problem with "multiple ternary operators", but when I tried to use it, I felt that there was a problem with readability.
• While doing a little brain teaser, it became a review of the Stream API and two birds with one stone.
• Recently, I've been away from Java for business, so I feel that the chances of touching the Stream API are decreasing.
• The information in the rangeClosed method that I looked up a while ago was also helpful.