Java - if statement vs ternary operator

Introduction

You can use the ternary operator in place of simple if-else statement.

The code is compact using the ternary operator.

Demo

public class Main {
  public static void main(String[] args) {
    String title = "";
    boolean isMale = true;

    if (isMale)//from   w  ww  .  j a va 2s .  c  om
      title = "Mr.";
    else
      title = "Ms.";

    System.out.println(title);

    // Using a ternary operator
    title = (isMale ? "Mr." : "Ms.");

    System.out.println(title);
  }
}

Result

The following code shows how to use a ternary operator in initialization.

Demo

public class Main {
  public static void main(String[] args) {
    int i = 10;/*from w w  w  .  j  a v a 2  s. com*/
    int j = 20;
    int k = (i < j ? i : j); // Using a ternary operator in initialization

    System.out.println(k);
    if (i < j)
      k = i;
    else
      k = j;

    System.out.println(k);
  }
}

Result

Using ternary operator in a function

Demo

public class Main {
  public static void main(String[] args) {
 
    int k = 15;//from w w w .j  a v a  2  s  .  com
    System.out.println(k == 15 ? "k is 15" : "k is not 15");
  }
}

Result

Related Topic