parsecer parsecer - 5 months ago 23
Java Question

Java ternary operator

I run a simple example of ternary operator. I wonder why in the second case it doesn't work.

class Gun
{
public int hit;
}

public class Test1 {
public static void main(String[] args) {
Gun weapon1=new Gun();
weapon1.hit=54;
String es1=new String("You killed him!. Grac!");
String es2=new String("Ops, you were noticed.");

System.out.println((weapon1.hit>50 ? es1 : es2)); //this works fine

weapon1.hit>50 ? System.out.println(es1) : System.out.println(es2); // this doesn't

}
}


After all, the ternary operator is supposed to work similar to if-else statements and this if-else code works just fine:

if (weapon1.hit>50)
System.out.println(es1);
else
System.out.println(es2);


Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement at Test1.main(Test1.java:39)
That's the error I get if I uncomment the
weapon1.hit>50 ? System.out.println(es1) : System.out.println(es2);
line.

Answer

The conditional is not simply equivalent to and if-else statement.

From the specification for the Conditional Operator ?:

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.

Comments