Reputation: 3833
I have been trying to implement the following condition in a more sofisticated manner:
if (x > 1)
doSomething();
else {
doSomethingElse();
}
want to code it like:
(x > 1) ? doSomething() : doSomethingElse();
Is this not possible at all?
Upvotes: 0
Views: 413
Reputation: 9601
You can write things like this:
i = (x > 1) ? doSomething() : doSomethingElse();
But not directly like this:
(x > 1) ? doSomething() : doSomethingElse();
Because in JLS §14.8:
14.8. Expression Statements
Certain kinds of expressions may be used as statements by following them with semicolons.
ExpressionStatement: StatementExpression ; StatementExpression: Assignment PreIncrementExpression PreDecrementExpression PostIncrementExpression PostDecrementExpression MethodInvocation ClassInstanceCreationExpression
There is no ConditionalExpression
in it.
Upvotes: 2
Reputation: 49372
Not possible if doSomething()
returns void
. Refer the JLS 15.25
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.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
Eventually the second and third operand should evaluate to the same type, how this evaluation is done is also mentioned in the JLS.
P.S: Why you want to doSomething()
for both true
or false
?
Upvotes: 4
Reputation: 3749
The ternary is used for inline if conditions. They need a return value, because u could write something like that:
System.out.println((x > 1) ? "True" : "False");
with void this would not be possible
Upvotes: 0
Reputation: 1193
It is dependent on return type.If you define like this void doSomething()
then its not possible.
Upvotes: 0
Reputation: 234665
Not in full generality; the arguments in the ternary (formally the ternary requires expressions) have to evaluate to the same type.
If doSomething() is a void
type then certainly not.
Upvotes: 1