Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this method work? Java ternary operator

What's wrong with this code:

void bark(boolean hamlet) {
    hamlet ? System.out.println("To Bark.") : System.out.println("Not to Bark");
}
like image 920
David West Avatar asked Jun 01 '13 19:06

David West


2 Answers

Ternary operators can't have statements that don't return values, void methods. You need statements that have return values.

You need to rewrite it.

void bark(boolean hamlet) {
     System.out.println( hamlet ? "To Bark." : "Not to Bark" );
}
like image 177
greedybuddha Avatar answered Nov 15 '22 15:11

greedybuddha


You can read why in the Java Language Specification, 15.25. Conditional Operator ? :

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

You need to do as several of the other answers suggest, and apply the conditional operator to just the argument.

like image 30
Keppil Avatar answered Nov 15 '22 13:11

Keppil