Java programming course: 5.8 The ternary operator

In the previous lesson you learnt about the if...else... block.


The ternary operator

There is a short-cut technique you can sometimes use in place of simple if...else... blocks. Consider the following code:

int temperature = 27;
String weather = "?";
if (temperature > 25) {
    weather = "hot";
} else {
    weather = "not hot";
}
 

The ternary operator allows you to combine the comparison with the assignment thus: 

// Using ternary operator
int temperature = 27;
String weather = temperature > 25 ? "hot" : "not hot";
 

Enter your text here ...

The ternary operator consists of a number of parts:

  • A variable to receive the result: i.e., String weather =
  • The condition to check: i.e., temperature > 25
  • The question mark symbol: ?
  • The value to assign if the condition is true: i.e., the string "hot"
  • A colon symbol :
  • The value to assign if the condition is false: i.e., the string "not hot"

In the next lesson you will learn about conditional statements using switch... case...:

Next lesson: 5.9 Conditionals using switch case


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image