Rico Strydom
Rico Strydom

Reputation: 549

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);

Upvotes: 0

Views: 156

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500535

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.

Upvotes: 5

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can't do that with Ternary operator in Java since setNull() is void method.

From §JLS.15.25:

ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression

The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.

The first expression must be of type boolean or Boolean, or a compile-time error occurs.

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

Upvotes: 3

Related Questions