Introduction to Java Ternary Operator:
In Java programming, the ternary operator, denoted by ? :
, provides a concise way to write conditional expressions. It’s often used as a shorthand for the if-else
statement when you need to assign a value to a variable based on a condition.
Syntax of the Java Ternary Operator:
The syntax of the Java ternary operator is:
variable = (condition) ? expression1 : expression2;
- If the condition evaluates to true,
expression1
is executed. - If the condition evaluates to false,
expression2
is executed.
Examples of Java Ternary Operator:
Let’s dive into some examples to understand how the Java ternary operator works.
- Basic Example:
int x = 10;
int y = 20;
int result = (x > y) ? x : y;
System.out.println("Result: " + result); // Output: 20
In this example, since the condition (x > y)
evaluates to false, the value of y
(20) is assigned to result
.
- Using Ternary Operator in a Method:
public static String getGrade(int score) {
return (score >= 60) ? "Pass" : "Fail";
}
public static void main(String[] args) {
int marks = 75;
System.out.println("Result: " + getGrade(marks)); // Output: Pass
}
This example demonstrates how to use the ternary operator within a method to determine a student’s grade based on their score.
- Nested Ternary Operators:
int num = 15;
String result = (num % 2 == 0) ? "Even" : (num % 3 == 0) ? "Divisible by 3" : "Odd";
System.out.println("Result: " + result); // Output: Divisible by 3
Here, the ternary operator is nested to check multiple conditions. If num
is even, “Even” is assigned. If not, it checks if num
is divisible by 3. If yes, “Divisible by 3” is assigned. Otherwise, “Odd” is assigned.
Conclusion:
In this tutorial, you’ve learned about the Java ternary operator, its syntax, and how to use it effectively with examples. Mastering the ternary operator can lead to more concise and readable code in your Java projects. Experiment with it in your own programs to become proficient in its usage.