Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write following code with Conditional(Ternary) Operator?

I am just playing with my code. The code in if else block can be written with conditional operator (? :). how to write following code with Conditional Operator.

  import com.itextpdf.text.Document;

public class TEst {
    public static void main(String[] args) {
        Document doc=null;
        try{
         doc=new Document();
        //some operation.
        }catch(Exception e){

        }finally{
            doc!=null? doc.close():"";

            //if(doc!=null){
            //  doc.close();
            //}
        }
    }

Eclipse suggestion :

Multiple markers at this line

  • Type mismatch: cannot convert from null to boolean

  • Syntax error on token "!=", invalid AssignmentOperator

like image 848
2787184 Avatar asked Mar 14 '23 00:03

2787184


2 Answers

You could use the ternary operator here (using a dummy boolean and not using it again):

boolean dummy = doc != null ? doc.close() : false;

But i would highly recommend not using this kind of code. If you think a "1-liner" might be readable here consider doing something like:

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

EDIT:

Explanation why not to use this kind of code:

You would create a boolean which is never used again without gaining anything.

  • The ternary operator is not faster than an if condition
  • The code becomes unreadable in this case
  • the boolean dummy still contains a boolean value if doc was null
like image 171
ParkerHalo Avatar answered Mar 31 '23 18:03

ParkerHalo


No. Ternary operator can't be used this way.

//if(doc!=null){
    //  doc.close();
    //}

If you closely look the code commented, there is no else part at all. You just have only if and ternary operator needs an else for sure. Hence not possible.

like image 27
Suresh Atta Avatar answered Mar 31 '23 18:03

Suresh Atta