Please demonstrate how the ternary operator works with a regular if/else block. Example:
Boolean isValueBig = value > 100 ? true : false;
Exact Duplicate: How do I use the ternary operator?
The programmers utilize the ternary operator in case of decision making when longer conditional statements like if and else exist. In simpler words, when we use an operator on three variables or operands, it is known as a Ternary Operator. We can represent it using ? : .
Ternary Operator in Java A ternary operator evaluates the test condition and executes a block of code based on the result of the condition. if condition is true , expression1 is executed. And, if condition is false , expression2 is executed.
It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.
Similarly the ternary operator in python is used to return a value based on the result of a binary condition. It takes binary value(condition) as an input, so it looks similar to an “if-else” condition block. However, it also returns a value so behaving similar to a function.
Boolean isValueBig = ( value > 100 ) ? true : false;
Boolean isValueBig;
if( value > 100 ) {
isValueBig = true;
} else {
isValueBig = false;
}
The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.
To use your example, changing from the use of a ternary expression to if/else you could use this statement:
Boolean isValueBig = null;
if(value > 100)
{
isValueBig = true
}
else
{
isValueBig = false;
}
In this case, though, your statement is equivalent to this:
Boolean isValueBig = (value > 100);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With