Saturday, January 11, 2025
HomeProgrammingTernary Operator in Java

Ternary Operator in Java

The ternary operator in Java is a shorthand for an if-else statement and is used to evaluate a boolean expression. It has the following syntax:

java

condition ? expression1 : expression2;

  • If condition is true, expression1 is executed; otherwise, expression2 is executed.
  • It returns a value based on the result of the condition and is often used for assigning values in a compact manner.
See also  How Do I Check for Null Values in JavaScript?

Example:

java

int x = 10, y = 20;

int max = (x > y) ? x : y;  // max will be assigned the value of y (20) because x is not greater than y.

The ternary operator improves readability and reduces code length, especially in simple conditional assignments. However, it should be used carefully for clarity when dealing with complex expressions.

Previous article
Next article
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x