import ballerina/io;function main (string[] args) {
int x = 20; string ifElseOutput;
if (x >= 50) {
ifElseOutput = "more than 50";
} else {
ifElseOutput = "less than 50";
}
io:println("The output from If-Else: " + ifElseOutput);
string ternaryOutput = x >= 50 ? "more than 50" : "less than 50";
io:println("The output from Ternary expression: " + ternaryOutput);
string nestedOutput = x >= 50 ? "more than 50" :
x >= 10 ? "more than 10" : "less than 10";
io:println("The output from nested ternary expression: " + nestedOutput);
}
TernaryThe Ternary Operator is a conditional operator, that can be used as a shortcut for an if-else statement. The ternary operator evaluates a condition and chooses one of two branches to execute. The ternary operator takes three operands and uses "?" and ":" symbols to form it. Syntax condition ? trueExpression : falseExpression |
|
import ballerina/io;
|
|
function main (string[] args) {
int x = 20;
|
|
string ifElseOutput;
|
|
if (x >= 50) {
ifElseOutput = "more than 50";
} else {
ifElseOutput = "less than 50";
}
io:println("The output from If-Else: " + ifElseOutput);
|
Writing a conditional statement using If-Else statement. |
string ternaryOutput = x >= 50 ? "more than 50" : "less than 50";
io:println("The output from Ternary expression: " + ternaryOutput);
|
writing above condition using ternary expression. |
string nestedOutput = x >= 50 ? "more than 50" :
x >= 10 ? "more than 10" : "less than 10";
io:println("The output from nested ternary expression: " + nestedOutput);
}
|
Writing nested conditions using ternary expression. |
$ ballerina run ternary.bal
The output from If-Else: less than 50
The output from Ternary expression: less than 50
The output from nested ternary expression: more than 10
|
|