Conditional Operator in Java

Video Tutorial
FREE
If Else thumbnail
This video belongs to
Java Course - Mastering the Fundamentals
12 modules
Certificate
Topics Covered

Conditional operators are used in programming just as we make decisions in real life. It controls the flow of the program and produces outcomes based on the provided conditions. There are three types of Conditional Operators: Conditional AND, Conditional OR and Ternary Operator. Let's dig and find out how and when these conditional operators are used in java.

Introduction to Conditional Operator in Java

Suppose you are given a number of regular polygons; you need to categorize them into their types. Three-sided polygon into a triangle, four-sided into a quadrilateral and so on. How do we execute these conditions and obtain the correct output? Here comes the role of Conditional Operators in Java.

Conditional Operators in Java are used to work on conditions. It is a unique operator used in place of 'If-else' statements. They make complex code much easy to write and understand. How? you ask! Let's dive in and and find out.

Three Types of Conditional Operator in java

There are three types of the conditional operators in Java:

  1. Conditional AND
  2. Conditional OR
  3. Ternary Operator

three types of conditional operator in java

Conditional AND (&&)

  • Syntax: &&

Below is the table representing the output of AND operator depending on the value of expressions:

expr1expr2expr1 && expr2
TTT
TFF
FTF
FFF

Below is an example of using AND Operator in a programmatic way to get a better understanding:

In the above example, AND operator checks for both conditions (age and gender) and evaluates to true as both expressions yields true values and produces the output: "Teenage girl";

The best way to remember the output of AND operator is: The output is only true whenever both the expressions surrounding the operator are true.

Conditional OR (||)

  • Syntax: ||

Below is the table representing the output of OR operator depending on the value of expressions:

expr1expr2expr1 II expr2
TTT
TFT
FTT
FFF

Let's create a Java program and use the OR conditional operator to get a better understanding:

A student is only eligible for camp if he builds projects or scores marks greater than 70. Here is logic to deduce whether a student is eligible for camp.

In the above example, one expression yields true, whereas the other yields false. Taking OR of both expression returns true as per the table shown above. So the resultant output becomes: Eligibe for Camp

The best way to remember the output of OR operator is: The output is only true whenever either of the expressions surrounding the operator is true.

Ternary Operator

The word ternary is the amalgamation of three parts. It is so named because it consists of three operands. A ternary operator is a condensed form of an if-else statement that evaluates a condition and executes the code based on the evaluated condition. Let's clearly understand how a ternary operator is written and used.

Teranry Operator Syntax:

result: The final variable which gets the value.

condition: This is the test condition statement that gets evaluated to true or false.

expression1: If condition gets evaluated to true then expression1 is assigned to result.

expression2 : If condition gets evaluated to false then expression 2 is assigned to result.

The only thing to remember when using ternary operation is: The very first operand must be a Boolean expression, and the second and third operands can be any expression that returns some value. image alt

If the above expression is written using If-else:

Example

Using Ternary Operator:

The above code checks the greater of the two variables, subtracts the smaller variable from the greater one, and stores the answer in the result. Both code gave the same output. The use of Ternary Operator compressed the 4-line code into just 1 line, making the code more comprehensive and readable.

When to Use Ternary Operator

Though at the byte code level, the Ternary Operator is not faster than if-else; it enhances the readability of code multiple times and makes it concise. Below are few examples how and when ternary operators can be used:

Ternary Operator Example

Example 1: Ternary operator as an alternative to if-else

Re-writing using Ternary Operator:

Example 2: Ternary operator as an alternative to if-else-if

Re-writing using Ternary Operator:

Example 3: Ternary operator as an alternative to switch-case

Let us consider a switch-case scenario.

Re-writing using Ternary Operator:

Hence, the ternary operator can be used to replace if-else, if-else-if and switch-case statements, making the code clearer and more optimized.

Expression Evaluation

When evaluating a ternary expression (condition), exp1: exp2. Only one of the two expressions, either exp1 or exp2, is evaluated at runtime. For instance, if the condition is true, then exp1 gets evaluated; otherwise, exp2. Let's understand this with some examples.

Our Condition always evaluates to true, so expression2 remained the same, and expression1 got incremented by 1.

Here, expression1 remains unchanged, and expression2 is incremented.

Nesting Ternary Operator

Java allows the feature of Nesting ternary Operator. Nesting means using a ternary operator inside another ternary operator. Let's have a look at the code to understand more about the nesting ternary operator.

nesting ternary operator

  • In the above program, we evaluated the value of the largest number using a nested ternary operator.
  • As illustrated in the diagram, the first expression (x>y) is evaluated and if it returns true then expression (x>z ? x : z) is evaluated else (y>z ? y : z) gets executed.
  • If expression1 (x>z ? x : z) gets executed, then it again checks the condition (x>z) and returns value according to the condition.
  • Similarly if expression2 (y>z? y : z) gets executed, then it checks for the condition (y>z) and returns the value according to the condition.
  • After executing all expressions, the result gets stored in largsetNum, and it all gets done using just a single code of line! Interesting right!

Ternary Operator as Null Check

Java ternary operator can also be used as a null check for an object before applying transformations to the object. Below is an example of how:

If null checks for objects are not considered, Null Pointer Exceptions are generated in codes, which can be avoided using the ternary operator. In the above code, the obj reference is null, so object. The getValue() method is not called, and it simply returns a null value.

Ternary Operator as max Function

Java ternary operator comes in handy to achieve the same functionality as the Java Math max() function . The example below is of implementing the Math.max() function using the ternary operator.

The above code utilized the max() function present in Java library, which takes two parameters, num1 and num2 and returns the maximum of two given numbers. Since 20>10 we got 20 as the output. The numbers can be int, float, double and long.

Using ternary operator to find the maximum of two numbers:

We observed that the ternary operator can easily be used in place of the inbuilt function to find the maximum of two numbers. The Ternary Operator helps readers understand the inner workings of code and how the logic is implemented to produce the correct output.

Ternary Operator as Min Function

The ternary operator can also be used as a min function, i.e., to calculate the minimum number of values, the same as the ** Java library min function, Math.min()**.

The above example demonstrated the use of the min() function in Java. It also takes two parameters and returns the smaller of the two values. Here, 10 is smaller than 20, so it produced 10 as its output.

Using ternary operator to find the minimum of two numbers:

Here, we can also see that the ternary operator can easily be used in place of the inbuilt function Math.min( ) to find the minimum of two numbers. Using the ternary operator helped us **** understand the logic behind the output more clearly.

Ternary Operator as abs Function

Java Ternary Operator can also be used to implement Java Math abs() function. Here's an example.

Benefits of Using Ternary Operator in Java

  • It is used as shorthand for if-else and switch-case statements.
  • It produces a comprehensive program with a reduced number of programming lines.
  • It makes the code more clear, concise and readable by scaling down the effective number of lines.
  • It can be nested to provide conditions within other conditions.
  • The ternary operator enables a form of "optional" parameter to easily inline a default choice when null is supplied for a parameter value.

Conclusion

  • Conditional Operators are used to work on conditions in Java. They control the flow of a program.
  • Ternary Operator is used in place of if-else, if-elseif and switch-case statements.
  • Ternary Operator enhances the conciseness and readability of code.

FAQs

Q. Does the condition of a Java Ternary operator always evaluate a boolean value?

A. Yes, the condition of a Java Ternary operator always evaluates to either true or false.

Q. Can the Ternary operator be used in place of if-else statements?

A. Ternary operators are used as shorthand for if-else statements.

Q. Does Java allow nested ternary operators?

A. Yes, Java allows the feature of the Nesting ternary operator.