Search code examples
javaconditional-operatorshorthand

How do I write this short hand in Java?


str = str.replace(fraction, replacement[1] || replacement[0]);

I want to replace with [1] if [1] is not "" or undefined or null, or else replace with [0] if [1] is "" or undefined or null. I know I can do this with a 3-5 lines of if else, but can I do it in one like very short like I wrote above in Java?


Solution

  • Java is not a very concise language by nature. The most concise way to do what you're asking is probably something like markspace's comment:

    str = str.replace(fraction, (replacement[1] != null && !replacement[1].isBlank()) ? replacement[1] : replacement[0]);
    

    This uses a ternary operator to select between replacement[1] and replacement[0].

    For a middle ground, you could also separate this ternary operation onto a separate line:

    char replacementChar = (replacement[1] != null && !replacement[1].isBlank()) ? replacement[1] : replacement[0];
    str = str.replace(fraction, replacementChar);