[Solved] Write 1 line If statement using ternary operator in JAVa


I assume your actual code looks like this:

if (preconditionflag.equals("skip")){
    System.out.println("Skipping this testcase due to earlier testcase failed");
    flag = "skip";
} else {
    flag = "pass";
}

If not, the answer to your question is already no, because you can’t return from a method in one part and not return from a method in the other part of the ternary operation.

The other obstacle speaking against a ternary operation here is the output on STDOUT. Ternary operators don’t allow that, but if you really need to you can solve it by creating a helper method:

private void myMethod() {
    ...
    flag = preconditionflag.equals("skip") ?
           showMessageAndReturn("Skipping this testcase due to earlier testcase failed", "skip") :
           "pass";
    ...
}

private String showMessageAndReturn(String message, String retVal) {
    System.out.println(message);
    return retVal;
}

This is an answer following your question exactly but I have difficulties to see an actual use for it in real life.

1

solved Write 1 line If statement using ternary operator in JAVa