If without else ternary operator

前端 未结 10 705
太阳男子
太阳男子 2020-12-05 17:04

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<

10条回答
  •  庸人自扰
    2020-12-05 17:30

    You cannot use ternary without else, but to do a "if-without-else" in one line, you can use Java 8 Optional class.

    PreparedStatement pstmt;
    
    //.... 
    
    Optional.ofNullable(pstmt).ifPresent(pstmt::close); // <- but IOException will still happen here. Handle it.
    

提交回复
热议问题