chevron_left
354 points
12 7 5

Though seldom used, ? operator have a significant usage in Java. Java include ? operator called ternary operator that can be used instead of certain if-then-else statements.

How it works?

Syntax : condition ? expression1 : expression2

Here, condition is a any expression which evaluates to a boolean value(true or false). If the condition evaluates to true, expression1 is executed and if the condition evaluates to false, expression2 is executed.

An easy code to manifest the ? operator usage:

x=10
y=25
max = x > y ? x : y

max is a variable which hold the resultant value, x > y is the condition determines the value. If the condition evaluates to true then the value x is assigned to the variable max, else if the condition evaluates to false then the value y is assigned to the variable max. Considering the values of x and y, the condition computes to false and thus value y is assigned to variable max.

max = 25

Code snippet to illustrate the ? operator:

public class TernaryOperator {
public static void main(String[] args) {		
	int x=10,y=25,min,max;
	min = x < y ? x : y;
	System.out.println("Minimum value : " + x);
	max = x > y ? x : y;
	System.out.println("maximum value : " + y);
}

}
In the above example, finding the minimum and maximum of two values using the ternary operator.

min = x < y ? x : y; -> As 10 < 25 condition evaluates to true, value x=10 is assigned to the variable min, hence min=10

max = x > y ? x : y; -> As 10 > 25 condition evaluates to false, value y =25 is assigned to the variable max and hence max = 25

We can implement the same scenario using if-else statements, but using the ternary operator is the simplest way which improves the readability and reduces the number of lines of code.

The output of this code:

Minimum value : 10
maximum value : 25

1 Comment

Operators play an important role in every language. You have explained about ternary operator or through information code which has made our practice easier.Thanks a lot  divyan.

More Posts

Java - Basic Operators Hasnain_khan - Oct 9, 2020
or operator in java DivyaN - Aug 16
java' is not recognized as an internal or external command Tania - Aug 14
In java, a function is a method that returns a value. true or false? kesav.eee - Jun 1
How to check if a number is in the Fibonacci Series or not using Java muliemes - May 17
Java program to check if a number is Palindrome or not amna - Apr 14
Java program to check if a number is prime or not amna - Apr 13
Error: "'java' is not recognized as an internal or external command, operable program or batch file Hasnain_khan - Oct 9, 2020
what does Increment ++ and Decrement -- Operator ? Hasnain_khan - Oct 13, 2020
What is o(n) in Java sakshi - Aug 21