-5

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?

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
Enrique_Iglesias
  • 121
  • 1
  • 2
  • 11
  • I have never heard of a negative variable before. What is it? Do you mean "a variable that has a negative numeric value"? – scottb Jun 03 '17 at 16:13
  • Yes it is.the variable 'i' is changed to '-i' in ternary operation. – Enrique_Iglesias Jun 03 '17 at 16:18
  • 1
    A better term would possibly be to *negate* the variable or as you're using it -- to get the variable's *absolute value*. – Hovercraft Full Of Eels Jun 03 '17 at 16:49
  • 1
    Read the Fine Manual http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html "Unary Operators" Also in the following subject the discussion of the conditional​ operator. – Lew Bloch Jun 03 '17 at 19:06

2 Answers2

3

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

int i = -10, k = Math.abs(i);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

It first checks

-10 < 0, which turns out to be true.

Thus, 'k' will be assigned with value -(-10) as i = -10. The result becomes 10.

Then you have the answer

-10 is 10 as value of i remains unchanged