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;
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;
}
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.
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);
This is using the ternary operator.
(
condition
?value1
:value2
) evaluates tovalue1
ifcondition
is true, otherwisevalue2
.The nested ternary expression:
amounts to:
It seems to be returning the maximum out of
a
,b
andc
, so it could be more clearly written as: