java – Ternary operator instead of if-else construction

Question:

Is it possible to improve (simplify) this construction with a ternary operator?

if (isLeftLetter && isRightLetter) {
    swap(chars, leftElementIndex, rightElementIndex);
    leftElementIndex++;
    rightElementIndex--;

} else {         
    if (!isLeftLetter) {
        leftElementIndex++;
    }

    if (!isRightLetter) {
        rightElementIndex--;
    }
}

Answer:

(isLeftLetter && isRightLetter) ?
    (swap(chars, leftElementIndex, rightElementIndex), leftElementIndex++, rightElementIndex--) :
    (
        (!isLeftLetter) ? leftElementIndex++ : leftElementIndex,
        (!isRightLetter) ? rightElementIndex-- : rightElementIndex
    );

It is still undesirable to use this design. As you can see, readability just got harder. But if this is your personal project and you yourself understand it, then your business.

Scroll to Top