Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If without else ternary operator

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>; 
like image 544
Z.V Avatar asked Nov 18 '13 16:11

Z.V


People also ask

Can you use ternary operator without else condition?

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.

How do you handle 3 conditions in a ternary operator?

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.

Which is better ternary operator or if else?

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).

Can we use else if in ternary operator?

The ternary operator, also known as the conditional operator, is used as shorthand for an if...else statement.


2 Answers

No, you cannot do that. Instead try this:

if(bool1 && bool2) voidFunc1(); 
like image 138
frankie liuzzi Avatar answered Oct 13 '22 21:10

frankie liuzzi


Why using ternary operator when you have only one choice?

if (pstmt != null) pstmt.close();  

is enough!

like image 24
cigno5.5 Avatar answered Oct 13 '22 21:10

cigno5.5