Search code examples
shortcut

Two variables from if else statement to ternary operator


In JAVA, what is the best way to convert the below code to use ternary operator:

if (input > 0) 
{
    result1 = input;
    result2 = input;
} 
else 
{
    result1 = -1;
    result2 = -1;
}

Solution

  • Short and Simple:

    result1 = result2 = input > 0 ? input : -1;