Apply Ternary operator on double value in Java

The ternary operator is also known as the conditional operator. This operator consists of three operands and is used to evaluate Boolean expressions.

Let’s say we have the following two double values.

double val1 = 20.0;
double val2 = 3.7;

Now, let us use the ternary operator to check for the first value.

System.out.println(val1 == 20 ? "Correct!" : "Incorrect!");

If the above condition is correct i.e. val is equal to 20, therefore first statement “Correct” will be returned. If it isn’t equal, then the second statement will get evaluated.

The following is the final example.


 Live Demo

import java.util.*;
public class Demo {
    public static void main(String args[]) {
       double val1 = 20.0;
       double val2 = 3.7;
       System.out.println("Checking first value " + val1);
       System.out.println(val1 == 20 ? "Correct!" : "Incorrect!");
       System.out.println("Checking second value " + val2);
       System.out.println(val2 == 3.8 ? "Correct!" : "Incorrect!");


Checking first value 20.0
Checking second value 3.7
Samual Sam
Samual Sam

Learning faster. Every day.