I have a simple if/elseif condition which I'm trying to convert it into a return statement with Ternay Operator for code redundancy but I have not been able to.
Any help would be appreciated, Thanks.
Here's my code snippet :
if (val.equals("a")||val.equals("s")){
return true;
}
else if (val.equals("b")||val.equals("t")) {
return false;
}
return true;
Could someone please suggest on how to proceed with return statement(Ternary Operator) for the above if/else-if ?
There's no need for a conditional operator here. Your code will return true
so long as val
is neither b
nor t
:
return !(val.equals("b") || val.equals("t"));
or:
return !val.equals("b") && !val.equals("t");
The first condition around a
and s
is completely irrelevant, as the "default" return true
at the bottom already includes those cases.
EDIT: Now that you've changed the return type to int
, this would be reasonable to use with the conditional operator:
return val.equals("b") || val.equals("t") ? 0 : 1;
See more on this question at Stackoverflow