The Wayback Machine - https://web.archive.org/web/20240717103918/https://www.geeksforgeeks.org/java-ternary-operator-with-examples/
Open In App

Java Ternary Operator with Examples

Last Updated : 01 Apr, 2024
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Operators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: 

  1. Arithmetic Operators
  2. Unary Operators
  3. Assignment Operator
  4. Relational Operators
  5. Logical Operators
  6. Ternary Operator
  7. Bitwise Operators
  8. Shift Operators

This article explains all that one needs to know regarding Ternary Operators. 

Ternary Operator in Java

Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for the if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.

Ternary Operator in Java


Syntax: 

variable = Expression1 ? Expression2: Expression3

If operates similarly to that of the if-else statement as in Exression2 is executed if Expression1 is true else Expression3 is executed.  

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Example:  

num1 = 10;
num2 = 20;

res=(num1>num2) ? (num1+num2):(num1-num2)

Since num1<num2,
the second operation is performed
res = num1-num2 = -10

Flowchart of Ternary Operation  

Flowchart for Ternary Operator

Examples of Ternary Operators in Java

Example 1: 

Below is the implementation of the Ternary Operator:

Java
// Java program to find largest among two
// numbers using ternary operator

import java.io.*;

class Ternary {
    public static void main(String[] args)
    {

        // variable declaration
        int n1 = 5, n2 = 10, max;

        System.out.println("First num: " + n1);
        System.out.println("Second num: " + n2);

        // Largest among n1 and n2
        max = (n1 > n2) ? n1 : n2;

        // Print the largest number
        System.out.println("Maximum is = " + max);
    }
}

Output
First num: 5
Second num: 10
Maximum is = 10

Complexity of the above method:

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2: 

Below is the implementation of the above method:

Java
// Java code to illustrate ternary operator

import java.io.*;

class Ternary {
    public static void main(String[] args)
    {

        // variable declaration
        int n1 = 5, n2 = 10, res;

        System.out.println("First num: " + n1);
        System.out.println("Second num: " + n2);

        // Performing ternary operation
        res = (n1 > n2) ? (n1 + n2) : (n1 - n2);

        // Print the largest number
        System.out.println("Result = " + res);
    }
}

Output
First num: 5
Second num: 10
Result = -5

Complexity of the above method:

Time Complexity: O(1)
Auxiliary Space: O(1)

Example 3:

Implementing ternary operator on Boolean values:

Java
// Java Program for Implementing 
// Ternary operator on Boolean values

// Driver Class
public class TernaryOperatorExample {
      // main function
    public static void main(String[] args)
    {
        boolean condition = true;
        String result = (condition) ? "True" : "False";
      
        System.out.println(result);
    }
}

Output
True

Explanation of the above method:

In this program, a Boolean variable condition is declared and assigned the value true. Then, the ternary operator is used to determine the value of the result string. If the condition is true, the value of result will be “True”, otherwise it will be “False”. Finally, the value of result is printed to the console.

Advantages of Java Ternary Operator

  • Compactness: The ternary operator allows you to write simple if-else statements in a much more concise way, making the code easier to read and maintain.
  • Improved readability: When used correctly, the ternary operator can make the code more readable by making it easier to understand the intent behind the code.
  • Increased performance: Since the ternary operator evaluates a single expression instead of executing an entire block of code, it can be faster than an equivalent if-else statement.
  • Simplification of nested if-else statements: The ternary operator can simplify complex logic by providing a clean and concise way to perform conditional assignments.
  • Easy to debug: If a problem occurs with the code, the ternary operator can make it easier to identify the cause of the problem because it reduces the amount of code that needs to be examined.

It’s worth noting that the ternary operator is not a replacement for all if-else statements. For complex conditions or logic, it’s usually better to use an if-else statement to avoid making the code more difficult to understand.



Previous Article
Next Article

Similar Reads

Java Ternary Operator Puzzle
Find the output of the program public class GFG { public static void main(String[] args) { char x = 'X'; int i = 0; System.out.print(true ? x : 0); System.out.print(false ? i : x); } } Solution: If you run the program,you found that it prints X88. The first print statement prints X and the second prints 88. The rules for determining the result type
2 min read
C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation. Syntax : op1 ? op2 : op3; Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like : a ? b : ca ? b: c ? d : e ? f : g ? h : ia ? b ? c : d : e Let us understand the syntaxes one by one : a ? b : c =&gt; T
5 min read
&amp;&amp; operator in Java with Examples
&amp;&amp; is a type of Logical Operator and is read as "AND AND" or "Logical AND". This operator is used to perform "logical AND" operation, i.e. the function similar to AND gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensiv
1 min read
&amp; Operator in Java with Examples
The &amp; operator in Java has two definite functions: As a Relational Operator: &amp; is used as a relational operator to check a conditional statement just like &amp;&amp; operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false. However, there is a slight difference between them, which h
2 min read
Diamond operator for Anonymous Inner Class with Examples in Java
Prerequisite: Anonymous Inner Class Diamond Operator: Diamond operator was introduced in Java 7 as a new feature.The main purpose of the diamond operator is to simplify the use of generics when creating an object. It avoids unchecked warnings in a program and makes the program more readable. The diamond operator could not be used with Anonymous inn
2 min read
Java Unary Operator with Examples
Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide. Here are a few types: Arithmetic Operators
8 min read
Double colon (::) operator in Java
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions. The only difference it has from lambda expressions is that this uses direct reference to the method by name instead of providing a delegate t
4 min read
Difference between concat() and + operator in Java
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-
6 min read
|| operator in Java
|| is a type of Logical Operator and is read as "OR OR" or "Logical OR". This operator is used to perform "logical OR" operation, i.e. the function similar to OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is true, i.e. it has a short-circuiting effect. Used extensively to test fo
1 min read
Shift Operator in Java
Operators in Java are used to performing operations on variables and values. Examples of operators: +, -, *, /, &gt;&gt;, &lt;&lt;. Types of operators: Arithmetic Operator,Shift Operator,Relational Operator,Bitwise Operator,Logical Operator,Ternary Operator andAssignment Operator. In this article, we will mainly focus on the Shift Operators in Java
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg