×

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be replaced with ternary operators, and they can even be used to build switch statements by nesting ternary operators. Even though it follows the same mechanism as an if-else statement, the conditional operator takes up less room and speeds up the writing process. It is a simplified if-else expression that yields a value. The only operator in Java that takes three operands is the ternary operator?:

Syntax

expression1 ? expression2 : expression3

Any expression that yields a value may be used as the second and third operands, but the first operand must be a Boolean expression. If the first operand evaluates to true, the ternary construct outputs expression1, else expression2.

The ternary or three way operator is similar to

int a=0;
if(Expression1)
{
    a = Expression2;
}
else
{
    a = Expression3;
}

Example

n1 = 20;
n2 = 30;
r = (n1>n2) ? (n1-n2):(n1+n2)
Since n1<n2, 
the second expression is performed
res = n1+n2 = 40

Ternary Operator Example

int n = 6;
String s = "" ;
if ( n > 20 ) {
    s = "Number is greater than 20";
}
else {
    s = "Number is less than or equal to 20";
}

Based on the conditional evaluation of num, we have here given the variable msg a value.

This code can be made safer and more readable by simply substituting a ternary construct for the if-else statement:

final String s = n > 20 ? "Number is greater than 20" : "Number is less than or equal to 20";

Program for Three way operator

Threeway.java

// Java program to explain about three way or ternary operator
// Importing java packages
import java.io.* ;
import java .util.* ;
class Main {
public static void main ( String [ ] s )
{
        Scanner sc=new Scanner (System .in );
// Declaration
System . out . println ( " Enter the first number " ) ;

int a = sc . nextInt ( ) ;
System . out . println ( " Enter the second number" ) ;
int b = sc . nextInt ( ) ;
int min ;
        // printing the first number
System . out . println ( " 1st  number is : " + a ) ;
// printing the second number
System . out . println ( " 2nd number : " + b ) ;


// Smallest among two numbers a and b is
min = ( a < b ) ? a : b ;
        // if a is less than b then a will be executed or else b will be executed and get stored in the variable min
// Printing  the smalllest number
System . out . println ( " Minimum is = " + min ) ;
}
}

Output

Enter the first number 
10
 Enter the second number
20
 1st  number is : 10
 2nd number : 20
 Minimum is = 10

 Java program for Three way operator

Threeway2.java

// Java code to illustrate ternary operator
// Java Packages importing 
import java . util . *;
import java.io.*;
// public class is declared with name Threeway2
class Threeway2 {
    // Main section of the program where execution starts
public static void main ( String [ ] s )
{
        // creating the object for scanner class
Scanner sc = new Scanner (System .in );
// Declaration
int a,b;
System . out . println ( " Enter the first number " ) ;
// initialisation of the variables
a = sc . nextInt ( ) ;
System . out . println ( " Enter the second number" ) ;
  b = sc . nextInt ( ) ;
        // printing the first number
System . out . println ( " 1st  number is : " + a ) ;
// printing the second number
System . out . println ( " 2nd number : " + b ) ;
// Performing three way operation
int r =  ( a > b ) ? ( a + b ) : ( a - b ) ;
// Printing the result 
System . out . println ( " Result = " + r ) ;
}
}

Output

Enter the first number 
10
 Enter the second number
20
 1st  number is : 10
 2nd number : 20
Result = -10

Related Topics

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

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...

3 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.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

All the important string methods 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 generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.