-1
(comparison > 0 ? n : m).subtract(comparison > 0 ? m : n);

I'm trying to figure out what this inline conditional statement means and how to convert it into a regular if statement. The .subtract is just a method that will subtract the second () from the first().

I think that the first (comparison > 0 ? n : m) is the same as if(comparison > 0) { m = n; } not sure how that works with the subtract function. The code runs correctly but I'm trying to fix the warning to not use inline conditionals.

Thank you!

2 Answers2

3

The ternary ?: operator is what is used here.

a ? b : c means

if (a) {
   b;
} else {
   c;
}

So (comparison > 0 ? n : m).subtract(comparison > 0 ? m : n); means.

if (comparsion > 0) {
    n.subtract(m);
} else {
    m.subtract(n);
}

In this case n and m must be objects that have a subtract method as follows which prints:

result = -3 when comparison = -5
result = 3 when comparison = 5

public class TernaryDemo {
    public static void main(String[] args) {
        for (int comparison : new int[] { -5, 5 }) {
            MyClass n = new MyClass(10);
            MyClass m = new MyClass(7);
            MyClass result = (comparison > 0 ? n : m)
                    .subtract(comparison > 0 ? m : n);

            System.out.println("result = " + result
                    + " when comparison = " + comparison);
        }
    }
}

class MyClass {
    int v;

    public MyClass(int v) {
        this.v = v;
    }

    public MyClass subtract(MyClass cls) {
        return new MyClass(this.v - cls.v);
    }

    public String toString() {
        return v + "";
    }

}
WJS
  • 36,363
  • 4
  • 24
  • 39
2

This is stuff you can test yourself.

However, it translates to:

Subtractable sub, sub2; // This is how I am going to call the class that has the subtract method

if(comparison > 0)
    sub = n;
else
    sub = m;

// You could put these in the same if statement, but this is closer to what actually happens.
if(comparison > 0)
    sub2 = m;
else
    sub2 = n;

sub.subtract(sub2);
cegredev
  • 1,485
  • 2
  • 11
  • 25