Java one line if does not work for prints

Viewed 3402

If you write something like:

    boolean condition;
    (...)
    String out = condition ? "true" : "false";
    System.out.println(out);

It works. But if you write

    condition ? System.out.println("true") : System.out.println("false");

you get a "not a statement" error. The "correct" way is to write (the usage of braces or "to be or not to be in one line" is out of the scope of the question):

    if (condition)
        System.out.println("true");
    else
        System.out.println("false");

Why? The one line ifs must always return a value?

EDIT: To everyone pointing out that

    condition ? System.out.println("true") : System.out.println("false");

is not a correct syntax, yeah I got that part. I am not asking for solutions (although the

    System.out.println(condition ? "true" : "false");

is nice.

@Andrew Tobilko where is that stated? THAT is what I'm interested in.

EDIT2: The accepted answer provides exactly what I wanted. Thanks

4 Answers
Related