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...:
Comments