Java Ternary Operator

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the ternary operator in Java to replace if-else statements. The ternary operator is used to write conditional statements in a single line, making the code cleaner and more readable. You will learn how to use the ternary operator and how to nest it.

The syntax of the ternary operator

The ternary operator is a shorthand way of writing if-else statements. The syntax of the ternary operator is as follows:

variable = (condition) ? expression1 : expression2;

Where condition is the boolean expression that is evaluated, expression1 is the value assigned to variable if condition is true, and expression2 is the value assigned to variable if condition is false.

Let's see an example:

int num1 = 50;
int num2 = 100;
int result;

result = (num1 > num2) ? num1 : num2;
System.out.println(result);

Output:

100

In the example above, if num1 is greater than num2, the value of result becomes num1, otherwise, the value of result becomes num2.

Using the ternary operator to replace if-else statements

We can use the ternary operator to replace if-else statements. Here is an example code that uses if-else statements to determine the eligibility of a person to vote:

int age = 18;
String message;

if (age >= 18) {
    message = "You are eligible to vote";
} else {
    message = "You are not eligible to vote";
}

System.out.println(message);

Output:

You are eligible to vote

We can replace the above code with a single line of code using the ternary operator, as shown below:

int age = 18;

String message = (age >= 18) ? "You are eligible to vote" : "You are not eligible to vote";

System.out.println(message);

Output:

You are eligible to vote

Nesting the ternary operator

We can also nest the ternary operators to write complex conditional statements. Here is an example code that uses nested if-else statements to determine the sign of a number:

int num = -10;
String sign;

if (num > 0) {
    sign = "Positive";
} else if (num < 0) {
    sign = "Negative";
} else {
    sign = "Zero";
}

System.out.println(sign);

Output:

Negative

We can replace the above code with a single line of code using nested ternary operators, as shown below:

int num = -10;

String sign = (num > 0) ? "Positive" : (num < 0) ? "Negative" : "Zero";

System.out.println(sign);

Output:

Negative

Summary

In this lab, you learned how to use the ternary operator to replace if-else statements in Java. You also learned how to nest the ternary operator for complex conditional statements. However, the ternary operator has some limitations and can only be used for simple if-else statements.

Other Java Tutorials you may like