Search code examples
javaconditional-operator

Write 1 line If statement using ternary operator in JAVa


Not sure its possible or not. I want to write 1 line if condition statement using ternary operator. Here is my code :

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

precondflag and flag are String paramaters. Also "else" part is optional to write so please provide code either with else part (flag = "pass") or without it. Thanks in advance.


Solution

  • 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.