So far from I have been searching through the net, the statement always have if and else condition such as a ? b : c
. I would like to know whether the if
ternary statement can be used without else
. Assuming i have the following code, i wish to close the PreparedStatement
if it is not null
(I am using Java programming language.)
PreparedStatement pstmt; //.... (pstmt!=null) ? pstmt.close : <do nothing>;
A ternary operation is called ternary because it takes 3 arguments, if it takes 2 it is a binary operation. It's an expression returning a value. If you omit the else you would have an undefined situation where the expression would not return a value. You can use an if statement.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).
The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement.
No, you cannot do that. Instead try this:
if(bool1 && bool2) voidFunc1();
Why using ternary operator when you have only one choice?
if (pstmt != null) pstmt.close();
is enough!
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