DEV Community

Alan
Alan

Posted on

Java by Example: If/Else

Condition branching with if and else in Java is straight-forward.

class Conditions {
  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");
    }

    // Here is an if-else-if branching example
    Integer 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");
    }

    // This is Ternary Operator; 
    // It enable testing a condition in single-line,
    // replacing the multi-line if-else tomaking the code compact.
    final String msg = num > 10 
      ? "9 is greater than 10" 
      : "9 is less than or equal to 10";
    System.out.println(msg);
  }
}
Enter fullscreen mode Exit fullscreen mode
javac Condition.java
java Condition
# 7 is odd
# 8 is divisible by 4
# 9 has 1 digit
# 9 is less than or equal to 10
Enter fullscreen mode Exit fullscreen mode

Top comments (0)