4

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

2787184
  • 3,749
  • 10
  • 47
  • 81

2 Answers2

4

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
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
3

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307