Search code examples
javaternarynegative-integer

Ternary operation with a "negative" variable


What does the negative variable do in a ternary? Why is the output -10 is 10?

public class Ternary {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i;
        System.out.print(i + " is " + k);
    }
}

Can anyone explain the function of the variable in this scenario? What does -i mean?


Solution

  • It's a unary operation -(-(1)) is 1. It's a longer way to write

    int i = -10, k = Math.abs(i);