Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What am I doing wrong with conditional operators? [duplicate]

Tags:

java

boolean

I have the following code:

public class boolq {
    public static void main(String[] args) {
        boolean isTrue = true;
        isTrue ? System.out.println("true"): System.out.println("false");       
    }
}

when I try to compile it i get this:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

Syntax error on token ";", assert expected after this token

Type mismatch: cannot convert from void to boolean

at boolq.main(boolq.java:3)

what am I doing wrong?

java -version

java version "1.6.0_15"

Java(TM) SE Runtime Environment (build 1.6.0_15-b03)

Java HotSpot(TM) Client VM (build 14.1-b02, mixed mode, sharing)

like image 840
Jakob Cosoroaba Avatar asked Jan 06 '10 00:01

Jakob Cosoroaba


1 Answers

The ternary operator is an expression, and evaluates to one of the two values that you pass to it.

Since System.out.println doesn't return a value, you can't put it inside the ternary operator.

You need to write System.out.println(isTrue ? "true" : "false");

like image 131
SLaks Avatar answered Oct 28 '22 18:10

SLaks