Ternary Operator in Java


A ternary operator uses 3 operands and it can be used to replace the if else statement. This can be done to make the code simpler and more compact.

The syntax of the ternary operator is given as follows −

Expression ? Statement 1 : Statement 2

In the above syntax, the expression is a conditional expression that results in true or false. If the value of the expression is true, then statement 1 is executed otherwise statement 2 is executed.

A program that demonstrates the ternary operator in Java is given as follows.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      Double num = -10.2;
      String str;
      str = (num > 0.0) ? "positive" : "negative or zero";
      System.out.println("The number " + num + " is " + str);
      }
}

Output

The number -10.2 is negative or zero

Now let us understand the above program.

The number num is defined. Then the ternary operator is used. If num is greater than 0, str stores “positive”, otherwise it stores "negative or zero". Then this is displayed for the specified number. The code snippet that demonstrates this is given as follows.

Double num = -10.2;
String str;
str = (num > 0.0) ? "positive" : "negative or zero";
System.out.println("The number " + num + " is " + str);

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements