Java by Example: If/Else and Ternary Operator

In Java, branching with if and else is straight-forward. An important note is that all conditions in Java must be enclosed within parentheses. Java also provides a compact way of writing if-else statements: the ternary operator.

Here are some basic examples:

public class Main {
    public static void main(String[] args) {

        // If-Else example
        if (7 % 2 == 0) {
            System.out.println("7 is even");
        } else {
            System.out.println("7 is odd");
        }

        // If without Else example
        if (8 % 4 == 0) {
            System.out.println("8 is divisible by 4");
        }

        // If-Else-If example
        int num = 9;
        if (num < 0) {
            System.out.println(num + " is negative");
        } else if (num < 10) {
            System.out.println(num + " has 1 digit");
        } else {
            System.out.println(num + " has multiple digits");
        }

        // Ternary operator example
        String result = (num % 2 == 0) ? "even" : "odd";
        System.out.println("The number is " + result);
    }
}

You can have an if statement without an else, use multiple if and else if statements, and use the ternary operator for more compact conditionals. However, for larger and more complex conditions, using traditional if-else statements can lead to more readable code.