×

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator.

Ternary operator in Java

A ternary operator is a kind of conditional operator used in Java. With appropriate examples, we shall take a glance about Java's ternary operator in this section.

The word "ternary" has three different meanings. Three operands make up the ternary operator (?:). To evaluate Boolean expressions, it is employed. The choice of value for the variable is made by the operator. In terms of accepting three operands, it's the only conditional operator. It can take the place of the if-else clause. The code is simplified, easier to read, and shorter as a result.

Syntax:

variable = (condition) ? expression1 : expression2

According to the preceding statement, if the condition evaluates to true, expression 1 is run; otherwise, expression 2 is executed, and the end result is saved in a variable.

Example of ternary operator

public class TernaryOperatorExample  
{  
public static void main(String args[])   
{  
int x, y;  
x = 20;  
y = (x == 1) ? 65: 90;  
System.out.println("Value of y is: " +  y);  
y = (x == 20) ? 65: 90;  
System.out.println("Value of y is: " + y);  
}  
}  

Output :

Value of y is: 90
Value of y is: 65

Let's look at another example where the ternary operator is used to determine which of three values is the largest.

LargestNumberExample.java

public class LargestNumberExample  
{  
public static void main(String args[])  
{  
int x=45;  
int y=32;  
int z=75;  
int largestNumber= (x > y) ? (x > z ? x : z) : (y > z ? y : z);  
System.out.println("The largest numbers is:  "+largestNumber);  
}  
}  

Output :

The largest numbers is:  75

We've used three variables with values of 69, 89, and 79 in the aforementioned program: x, y, and z. The statement (x > y)? The formula (x > z? x: z): (y > z? y: z) determines which of three numbers is the largest and stores the result inside the variable largestNumber. Let's examine the expression's execution hierarchy.

It first validates the statement (x > y). The expression (x > z? x: z) is executed if it returns true; else, the expression (y > z? y: z) is executed.

It first validates the statement (x > y). Whenever the expression (x > z? x: z) is run, it tests the condition x > z to see if it returns. The value of x is returned if the condition gets true; else, the result of z is returned. If the statement (x > z? x: z) is true, then the statement (y > z? y: z) is true.

When the equation (y > z? y: z) is run, the assumption that y > z is further verified. A value of y is delivered if the condition gets true, otherwise the result of z is returned.

As a result, we may use the ternary operator to find the greatest of the three numbers.

When is the Ternary Operator appropriate?

It Is used for if – else statements,

class Main {
  public static void main(String[] args) {
    // establish a variable
    int number = -13;


    if(number > 0) {
      System.out.println ("Positive Number");
    }
    else {
      System.out.println ("Negative Number");
    }
  }
}

Output :

-ve Number

Nested Ternary Operators

One ternary operator can also be used inside of another ternary operator.

Here, is a program to display ternary operators in java

class Main {
  public static void main(String[] args) {
    // create a variable
    int n1 = -22  n2 = 32,  n3 = 21;


    // nested ternary operator
    // for finding the  largest number
    int largest = (n1 >= n2)  ?  ((n1 >= n3) ? n1 : n3)   :  ((n2 >= n3) ? n2 : n3);
    System.out.println("Largest Number: " + largest);
  }
}

Output :

Largest Number: 32

Here,

  • The first test condition is (n1 >= n2), which determines whether n1 is bigger than n2.
  • If the first condition is true, the second test condition (n1 >= n3) is carried out.
  • If the initial condition becomes false, the third test condition, (n2 >= n3), is carried out.

Related Topics

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Alien language problem in Java

Given the alphabetic sequence of an alien language, given a sorted dictionary (array of words) for the languages. Example: Words = { "aac", "abc", "aaa" } Output c, a, b Algorithm: (1) Compare two words that...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Chromatic Number in Java

The chromatic number is the bare minimum of colours necessary to accurately colour any graph. To put it another way, the chromatic number can be thought of as the bare...

6 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Local Minima in Java

An Array Finding a local minimum in an array a[0. m-1] of different integers is the job. A[i] is considered a local minimum if it is smaller than two of its...

4 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.