Tutorial

Java Ternary Operator

Published on August 3, 2022
author

Pankaj

Java Ternary Operator

Java ternary operator is the only conditional operator that takes three operands. Java ternary operator is a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator to replace switch also as shown in below example.

Java Ternary Operator

java ternary operator The first operand in java ternary operator should be a boolean or a statement with boolean result. If the first operand is true then java ternary operator returns second operand else it returns third operand. Syntax of java ternary operator is: result = testStatement ? value1 : value2; If testStatement is true then value1 is assigned to result variable else value2 is assigned to result variable. Let’s see java ternary operator example in a simple java program.

package com.journaldev.util;
 
public class TernaryOperator {
 
    public static void main(String[] args) {
         
        System.out.println(getMinValue(4,10));
         
        System.out.println(getAbsoluteValue(-10));
         
        System.out.println(invertBoolean(true));
         
        String str = "Australia";
        String data = str.contains("A") ? "Str contains 'A'" : "Str doesn't contains 'A'";
        System.out.println(data);
        
        int i = 10;
        switch (i){
        case 5: 
        	System.out.println("i=5");
        	break;
        case 10:
        	System.out.println("i=10");
        	break;
        default:
        	System.out.println("i is not equal to 5 or 10");
        }
        
        System.out.println((i==5) ? "i=5":((i==10) ? "i=10":"i is not equal to 5 or 10"));
    }
 
    private static boolean invertBoolean(boolean b) {
        return b ? false:true;
    }
 
    private static int getAbsoluteValue(int i) {
        return i<0 ? -i:i;
    }
 
    private static int getMinValue(int i, int j) {
        return (i<j) ? i : j;
    }
 
}

Output of the above ternary operator java program is:

4
10
false
Str contains 'A'
i=10
i=10

As you can see that we are using java ternary operator to avoid if-then-else and switch case statements. This way we are reducing the number of lines of code in java program. That’s all for a quick roundup of ternary operator in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
March 7, 2019

System.out.println(“You guys reason well. That’s why i believe you are programmers.”);

- Adam

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 13, 2018

    Switch case is better than if else in performance wise. Ternary operator is better for simple conditions.

    - anil reddy

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      March 14, 2018

      1. mostly use switch which is more efficient 2. if you can’t use switch in some cases like non-matching stuff of strings use if… elseif…else 3.use ternary rarely in easy & simple cases eg : if (a == true) { sop(“true”); else { sop false } a = (a = true) ? “true” : “false”; don’ t use in cases like : int age = 29; if (age < 13) { System.out.println(“You are but a wee child!”); }// end if for age < 13 else if (age < 19) { System.out.println(“You are no longer a child, but a budding teenager.”); } // end else if for age < 19 else { if (age < 65) { System.out.println(“You are an adult!”); }// end if for age < 65 else { System.out.println(“You are now a senior, enjoy the good life friends!”); } // end if for nested else System.out.println(“Also, since you are over the age of 19, you deserve a drink!”); }// end of final else

      - sriram.c

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 5, 2017

        This was really helpful?

        - Yashi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 3, 2014

          Hi Pankaj, Performance wise which one is better: 1) if then … else 2) switch 3) ternary operator

          - Abhi

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Featured on Community

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more