If Else in CLIPS

Branching with if and else in Java is straightforward.

public class IfElse {
    public static void main(String[] args) {
        // Here's a basic example.
        if (7 % 2 == 0) {
            System.out.println("7 is even");
        } else {
            System.out.println("7 is odd");
        }

        // You can have an `if` statement without an else.
        if (8 % 4 == 0) {
            System.out.println("8 is divisible by 4");
        }

        // Logical operators like && and || are often useful in conditions.
        if (8 % 2 == 0 || 7 % 2 == 0) {
            System.out.println("either 8 or 7 are even");
        }

        // A statement can precede conditionals; any variables
        // declared in this statement are available in the current
        // and all subsequent branches.
        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");
        }
    }
}

To run the program, compile and execute it using javac and java:

$ javac IfElse.java
$ java IfElse
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Java, you need parentheses around conditions, and the braces are required for multi-line blocks but optional for single-line blocks.

Java does have a ternary operator (?:) which can be used for simple conditional expressions:

String result = (x % 2 == 0) ? "even" : "odd";

This is equivalent to:

String result;
if (x % 2 == 0) {
    result = "even";
} else {
    result = "odd";
}

The ternary operator can be useful for simple conditions, but for more complex logic, a full if-else statement is often more readable.