×

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

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

AES 256 Encryption in Java

Now a days, security has grown in importance. Java programming supports a variety of encryption and hashing methods, which offers security for data transport and communication among various nodes. In...

4 minutes read.

Java Xml Parser

In this article, we acknowledge you about what is a XML parser in Java, how is it going to work and what is the purpose of it. Also, the article discusses...

6 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

String Handling Method in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.