Home > Net >  refactoring if else to Single line conditional statement in Java?
refactoring if else to Single line conditional statement in Java?

Time:11-11

I want to write single line if else check. But i am getting error.

Please help

if(x == 1) {
    System.out.println("aaa");
}else {
    System.out.println("bbb");
}

Is there a way to make above code as single like below. Getting compile error in below line

x == 1 ? System.out.println("aaa") : System.out.println("bbb");

Please help. I might be making a silly error i guess.

CodePudding user response:

The second and third arguments of the conditional ternary expression must be expressions, so they can't be System.out.println("aaa").

Instead, so you can write:

System.out.println (x == 1 ? "aaa" : "bbb");

Now you have a ternary conditional expression that produces a value (either "aaa" or "bbb"), and that value is passed to System.out.println.

CodePudding user response:

The ternary operator can only be used with expression returning a value. In your case, System.out.println("aaa") is not expression and can't be used.

You can use:

System.out.println(x == 1 ? "aaa" : "bbb");
  • Related