Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the ternary operator work?

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?

like image 963
Sara S Avatar asked Jan 20 '09 21:01

Sara S


People also ask

How does ternary operator work in C?

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

How does ternary operator work java?

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.

How do you use a ternary operator example?

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.

How does the ternary operator work in Python?

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.


2 Answers

Boolean isValueBig = ( value > 100  ) ? true : false;


Boolean isValueBig;

if(  value > 100 ) { 
      isValueBig = true;
} else { 
     isValueBig = false;
}
like image 178
Kent Fredric Avatar answered Oct 04 '22 00:10

Kent Fredric


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);
like image 45
Dan Monego Avatar answered Oct 03 '22 23:10

Dan Monego