Java: meaning of operand statement

142 views Asked by At

I found this statement in a classmate's code, and I do not know what it means. I cannot figure out the order of operations or the meaning from there.

Thanks in advance

return a > b ? a > c ? a : c : b > c ? b : c;

6

There are 6 answers

0
khelwood On

This is using the ternary operator.

(condition ? value1 : value2) evaluates to value1 if condition is true, otherwise value2.

The nested ternary expression:

return a > b ? a > c ? a : c : b > c ? b : c

amounts to:

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

It seems to be returning the maximum out of a, b and c, so it could be more clearly written as:

return Math.max(a, Math.max(b,c));
0
depperm On

If a>b true then if a>c true then a else c. if a>b false then b>c then b else c

0
Abhijeet Dhumal On

If you write the statement in if else's it will look like this:

if (a > b) {
    if (a > c) {
        return a;
    } else {
        return c;
    }
} else {
    if (b > c) {
        return b;
    } else {
        return c;
    }
}
0
Balkrishna Rawool On

In Java this construct (?:) is referred as ternary operator. This is how it works:

a=(b?c:d)

This means a is assigned value of c if expression b is true and a is assigned value of d if expression b is false.

In your case

return a > b ? a > c ? a : c : b > c ? b : c;

This means if a > b is true then check if a > c. if a > c then return a otherwise return c. if a > b is false then check if b > c. if b > c then return b otherwise return c. which is equivalent to:

if (a > b) {
    if (a > c) {
        return a;
    } else 
        return c;
} else {
    if (b > c) {
        return b;
    } else 
        return c;
}
0
moltom26 On

See this question here: what-is-the-java-operator-called-and-what-does-it-do Pretty much it is saying, return a if a > b and a > c, else return c else, if b > c, return b, else return c.

0
Jose Cifuentes On

Another answer is that:

return a > b ? a > c ? a : c : b > c ? b : c;

Means (parenthesized to make more readable):

return ((a>b) ? ((a>c)?(a):(c)) : ((b>c)?(b):(c)));

Which is using a ternary operator, that translates (English) to:

If a greater than b AND a greater than c, return a. If a greater than b AND a less or equal than c, return c. If a less or equal than b AND b greater than c, return b. If a less or equal than b AND b less or equal than c, return c".

Which is simply determining the largest value of a triple. You could do something like this which is much simpler and easier to read:

return Math.max(Math.max (a,b),c);