Java ternary operator examples

Posted in /  

Java ternary operator examples
ramyashankar

Ramya Shankar
Last updated on December 21, 2024

    Java ternary operators make the code short and easy to understand. They can replace an entire set of if..else..then statements and also perform a lot of logical (Boolean) operations on the right-hand side of the statement in less amount of code. The operators work on Boolean expressions, i.e., either a Boolean field or statement that gives a Boolean result.

    Java Ternary operator

    Before learning further about the ternary operator, let us understand how a basic if…else statement in Java works:

    int tempC = 0;
    System.out.println("Enter temperature in Celsius: ");
    Scanner scan = new Scanner(System.in);
    try{
    tempC = scan.nextInt();
    }catch (Exception exc){
    System.out.println("Enter a valid number");
    System.exit(0);
    }
    if(tempC > 40)
    System.out.println("Oh! Its too hot!");
    else
    System.out.println("Stay home and enjoy the weather!");

    In the above program, we take the user's temperature and, based on simple if..else, print a message for the user. We are using a lot of lines of code here. Using the Java ternary operator, we can reduce the code to just one line and get the same results:

    weather = (tempC > 40) ? "Oh! It's too hot!" : "Stay home and enjoy the weather!";
    System.out.println(weather);

    Note that the syntax of the ternary operator is:

    condition ? expression1 : expression2;

    The program checks if the condition is true. If true, expression1 is executed; else, expression2 is executed. Both expressions can be anything, as we will see in the next example.

    System.out.println("Enter two numbers to compare, separated by white space..");
    int a = scan.nextInt();
    int b = scan.nextInt();
    System.out.println("Which is lesser: " + a + " or " + b + "?");
    int minval = (a<b) ? a : b;
    System.out.println("The smaller one is: " + minval);
    System.out.println("Which is bigger: " + a + " or " + b + "?");
    int maxval = (a>b) ? a : b;
    System.out.println("The greater one is: " + maxval);

    Notice that the value of minval and maxval is evaluated using a single statement. Also, the first result is always the result of true condition and the second is false. So, we can say that:

    result = condition ? trueValue : falseValue;

    We can embed ternary operators in String to print a proper statement:

    Child child = new Child("John", true);
    String result = "Congrats, " + child.getName() + ", you won a " + (child.isBoy() ? "Superman" : "Wonderwoman") + " as gift!";

    This will give:

    Congrats, John, you won a Superman as a gift!

    We can also nest ternary operators: Let us say we have to find smallest of three numbers:

        int a = 10, b = 0, c = -10;
        // find the smallest number
        int smallest = (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c);
    
        System.out.println("smallest Number: " + smallest);

    First, we compare a & b, and the smaller of the two is then compared with c to get the final smallest value.

    Conclusion

    We have seen how ternary operators can evaluate an expression and result in just one line of code. We can execute expressions, functions with return value Boolean, add strings, or any other value types to get the final result. We can also nest the ternary operators to check for more than two conditions, but it is complex and not easy to comprehend.

    People are also reading:

    Leave a Comment on this Post

    0 Comments