Java Ternary Operator With Examples

May 02, 2022
Java Developers



Introduction

A ternary operator is not a new thing for programmers. It is part of the syntax for basic conditional expressions in almost every modern programming language. We commonly refer to it as the conditional operator, inline if (iif), or ternary if. It works similar to the If-conditional statement but it is a single-line statement. Let’s discuss the ternary operator in java with some examples.

 

Ternary operator in Java

The ternary operator in Java is a part of conditional statements. As the name ternary suggests, it is the only operator in Java that consists of three operands. The Java ternary operator can be thought of as a simplified version of the if-else statement with a value to be returned. It consists of a Boolean condition that evaluates to either true or false, along with a value that would be returned if the condition is true and another value if the condition is false.

explore new Java roles

Syntax of the ternary operator in Java

The syntax of the java ternary operator includes two symbols, “?” and ”:” See this line of code below:

Datatype var1 = <boolean Expression> ? <value1> : <value2> ;

The variable var1 on the left-hand side of the = (assignment) operator will be assigned, value1 if the Boolean expression evaluates to true or value2 if the Boolean expression evaluates to false.

See this Java code example for checking if the integer is even or odd, first using a simple if-else statement then using a ternary operator in Java.

Using if-else statement:

1. public static void main( String args[] ) {
2.    int num = 3;
3.    if(num % 2 == 0)
4.     {
5.      System.out.println("This is an even number!");
6.     }
7.    else
8.     {
9.      System.out.println("This is an odd number!");
10.    }
11.  }
12. }

Now the same functionality using the ternary operator in Java:

1.public static void main( String args[] ) {
2.    int num = 3;
3.    String msg = (number % 2 == 0) ? "This is an even number!" : "This is an odd number!";
4.    System.out.println(msg);
5.  }
6. }

Ternary operator condition

The condition part of the above ternary operator expression is this part:

(number % 2 == 0)

The condition is a Java expression that evaluates to either true or false. The above condition will evaluate to true if the num is completely divisible by 2, which means it is an even number or false if it is not.

The condition can only be a Java expression that evaluates to a Boolean value, just like the expressions we use in an if-else statement or a while loop. A non-Boolean statement such as an assignment statement or an input/output statement here will result in a syntax error.

Ternary operator values

Right after the condition of a ternary operator we have a question mark (?) followed by two values, separated by a colon (:) that the ternary operator can return. The values part of the ternary operator in the above example is this:

“This is an even number!” : “This is an odd number!”;

In the example above, if the condition evaluates to true then the ternary operator will return the string value “This is an even number!”. If the condition evaluates to false then the ternary operator expression would return the string value “This is an odd number!”; .

The returning values can consist of any data type or can be the result of a Java expression that returns a value of any data type but it should be the same as the data type of the variable it is assigned to. The Java variable (msg) at the start of the ternary operator is of type String, then the values returned by the values must also be of type String. In the case of dissimilar data types, the code will result in a syntax error.

Using a ternary operator for null checks

As ternary operator takes relatively less space as compared to an if-else statement, it is feasible to be used as a shorthand for null checks before calling a method on an object. See this code snippet:

String val01 = obj01 != null ? obj01.getValue() : null;

Now see this one demonstrating the same null check using an if statement:

1. String val01 = null;
2. if(object != null) {
3.    value = obj1.getValue();
4. }

Both examples are equivalent to each other, but the ternary operator example is a bit shorter and more elegant, making the code more readable.

Implementing math functions with ternary operator in Java

It could seem pointless at first as the math functions are already very straight forward but there could be many scenarios where you could be incapable of using them then ternary operator can be a very good alternative due to its short format.

· Using a ternary operator to find the maximum value

There is a simple function in math class in Java to find the maximum number but you can also achieve the same functionality using a ternary operator in Java. See this code snippet used to find the maximum number using the ternary operator in Java:

1. int num1 = 34;
2. int num2 = 3;
3. int maxNum = num1 >= num2 ? num1 : num2;

If the num1 value is larger than or equal to the num2 value. the ternary operator will return the num1, else it will return the value in num2.

· Using a ternary operator to find the minimum value

Just like the maximum, the Java ternary operator can also be used to find the minimum number like the Java Math min() function. See this example below:

1. int num1 = 34;
2. int num2 = 3;
3. int minNum = num1 <= num2 ? num1 : num2;

· Using a ternary operator to find the absolute value

Now to find the absolute value, see this example the ternary operator in Java:

1. int num1 = 34;
2. int absolute = num1 >= 0? num1 : -num1;

The ternary operator conditions will first check if the value in num1 is larger than or equal to 0. In that case, the ternary operator returns the value as it is else it will return -num1, which will negate the negative value, turning it positive.

Nested ternary operator in Java

Just like nesting in if-else statement, you can do that using Ternary Operator in Java by chaining more than one Java ternary operator together. It is done by implementing another ternary operator in place of one or both of the values. See this example of a chained ternary operator in Java:

1. public static void main(String[] args) {
2.    int num1 = 44, num2 = 12, num3 = 2;
3.    int Largest = (num1 >= num2) ? ((num1 >= num3) ? num1 : num3) : ((num2 >= num3) ? num2 : num3);
4.    System.out.println("The largest Number is: " + Largest);
5.  }

Here we are also trying to find the maximum number, but now we have three values to compare.

The first ternary operator condition compares the num1 and num2 numbers just like before but the values to be returned are different here. In both conditions, a second ternary operator comparing the largest value with the third number stored in num3. The second ternary operator will then return the largest number among all three.

You can chain or nest the Java ternary operator multiple times as much as you want, as long as each ternary operator returns a single value, and each ternary operator is used in place of a single value.

It is still preferred not to use nesting as it makes the code more complex and difficult to make any amendments later.

See Also: Adding a Newline Character To a String In Java

Conclusion

Ternary operator in Java is neither a novelty nor an exceptional feature for Java developers but it can surely be a worthy addition to your Java tool kit. Ternary operator can come in handy if your code consists of several if-else statements at different places as it can significantly shorten your code by using ternary operator instead of “if statements”.

new Java jobs



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US