How to write the following code with a conditional (triple) operator?

I just play with my code. The code in the if else block can be written with a conditional statement (? :). how to write the following code with a conditional statement.

  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:

Several markers on this line

  • Type mismatch: cannot convert from null to boolean

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

+4
source share
2 answers

Here you can use the ternary operator (using a dummy logical and not using again):

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

. , "1-" , - :

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

EDIT:

, :

, , .

  • , if
  • boolean dummy - , doc null
+4

. .

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

, . , . , .

+3
source

Source: https://habr.com/ru/post/1617960/


All Articles