Java operator ? :

How can I change

if(xmlComboBoxValues.get(0) == null){
    cstmt.setNull(i++,java.sql.Types.NVARCHAR); 
}
else {  
    cstmt.setString(i++, (String) xmlComboBoxValues.get(0));            
}

as a ? : expressing in java?

Here is what I have but the syntax is obviously wrong.

xmlComboBoxValues.get(0) == (null) ? cstmt.setNull(i++,java.sql.Types.NVARCHAR) : cstmt.setNull(i++,java.sql.Types.NVARCHAR);
Jon Skeet
people
quotationmark

You can't do that for two reasons:

  • The methods have a void return type
  • You can't use a conditional expression as a statement

These are both symptoms of the same cause: you're misusing the operator. The purpose of the operator is to choose which of two expressions to use as the result of the overall expression... which is then used for something else. Computing an expression has slightly different aim from executing a statement.

Your original code is already idiomatic: if a condition is true, you want to execute one statement. Otherwise, you want to execute a different statement. Perfect for if/else.

people

See more on this question at Stackoverflow