Search code examples
javaif-statementreturnconditional-statementscode-cleanup

How do you return a boolean by comparing three variables on the same line?


I've seen people doing an if and else statement on only 1 line using

return var1 != null ? var2 : 0;.

This seems quite more compact and quicker to type than making an if statement and then a few more lines and so on...

The return statement above is an example, I could not recreate something similar as I don't know the syntax of using if and else statements on return lines.


The current situation:

There are 3 integers.

I want to compare if var 1 is bigger than var 2 and also (&&) if (var 1 + var 3) is bigger than var 2. If those conditions are true then the return statement should return false else true.

Attempt:

return var1 > var2 && (var1 + var3) > var2 ? false : true;

Solution

  • "If var1 is bigger than var2" is this condition:

    var1 > var2
    

    "If var1 + var3 is bigger than var2" is this condition:

    var1 + var3 > var2
    

    Return false if both those conditions match, otherwise true:

    return !(var1 > var2 && var1 + var3 > var2);
    

    Alternatively, you can negate the individual conditions, which gives:

    return (var1 <= var2 || var1 + var3 <= var2);
    

    (which is equivalent as long as none of your numbers is NaN.)

    There is no need for the ?: operator.