×

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

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Bellman Ford Algorithm in Java

Numerous algorithms have been used in dynamic programming to determine the shortest path inside a graph. Among them are Floyd, all-pair shortest path problem, Breadth First Search, Depth First Search,...

6 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

How to Send SMS in Java with Example

Sending SMS messages in Java is a fairly common task, and there are a number of libraries and APIs available to help you do it. One popular option is to...

2 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

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

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.