Skip to content

Commit e28dcbe

Browse files
12.7. Conditional Operator: Introduce chaining ternay operators
1 parent 7f43e1a commit e28dcbe

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/branching_logic/conditional_operator.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,31 @@ and then a value to use when that condition evaluates to `false`.
2323
CONDITION ? WHEN_TRUE : WHEN_FALSE
2424
```
2525

26+
Just like multiple if else statements, we have the concept to "chain" ternary operators. If the first condition is not true, it goes to the next condition and so on.
27+
28+
```java
29+
~void main() {
30+
int age = 22;
31+
32+
String message = age < 0
33+
? "You are not born yet"
34+
: age > 100
35+
? "Sorry, you are too old."
36+
: age < 25
37+
? "You cannot rent a car!"
38+
: "You might be able to rent a car";
39+
40+
IO.println(message);
41+
~}
42+
```
43+
44+
It is same as before, you write a condition followed by a `?`, a value to use when that condition evaluates to `true`, a `:`,
45+
and then _chain_ another condition to use when that condition evaluates to `false`.
46+
47+
Finally, if no condition was true, it matches the value after the final `:`.
48+
49+
```java,no_run
50+
CONDITION ? WHEN_TRUE : CONDITION ? WHEN_TRUE : CONDITION ? WHEN_TRUE ... : WHEN_ALL_FALSE
51+
```
52+
2653
[^ternary]: Some people will call this a ternary expression. Ternary meaning "three things." Same idea as tres leches.

0 commit comments

Comments
 (0)