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
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.
dummy
still contains a boolean value if doc
was null
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With