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>;
As mentioned in the other answers, you can't use a ternary operator to do this.
However, if the need strikes you, you can use Java 8 Optional and lambdas to put this kind of logic into a single statement:
It does seem a shame not to be able to use a ternary when building an array which has optional elements.
You really want nothing rather than undef or empty string.
This also gives you an empty element rather than 'nothing'.
Why using ternary operator when you have only one choice?
is enough!
Just write it out?
It's the exact same length.
You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8
Optional
class.No, you cannot do that. Instead try this: