Sangli
Sangli

Reputation: 363

Conditions in Ternary Operator - Java

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 ?

Upvotes: 0

Views: 297

Answers (5)

Jon Skeet
Jon Skeet

Reputation: 1500175

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;

Upvotes: 6

Michael
Michael

Reputation: 2942

return !(val.equals("b") || val.equals("t"))

Upvotes: 0

tmarwen
tmarwen

Reputation: 16354

Try the follwing:

boolean b = ( val.equals("b") || val.equals("t") ) ? false : true;
return b;

Upvotes: -1

Jack
Jack

Reputation: 3059

return !(val.equals("b") || val.equals("t"));

This is the only condition that returns false - so you don't need to check the first condition.

Upvotes: 2

amit
amit

Reputation: 178421

return !(val.equals("b") || val.equals("t"))

The rest is redundant, val cannot equal "a" or "s" and equal "b" or "t" at the same time, so you basically need to check if it equals "b" or "t", and return false in this case, and true in any other case.

Upvotes: 4

Related Questions