mercredi 23 mars 2016

Java one line if does not work for prints

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?

Aucun commentaire:

Enregistrer un commentaire