Search code examples
javaternary-operator

printing operation with the ternary


I often use the following if block (no else/elseif clauses;just for a specific check)

if(value==10){system.out.print("true");}

So I tried using it with the ternary:

(a==1)?System.out.println("true");

but it is not working. Mainly, I wanted to know that does ternary operator can act like a single if? (and although I haven't pondered over it, but can it work like an if-else_if-else clause?)


Solution

  • What you are trying to achieve isn't possible. If you must use a ternary, though, try this

    String a = (value==10) ? "Yes" : "No";
    System.out.println(a);
    

    Otherwise you can also do this,

    System.out.println((value==10)?"Yes":"No");