Skip to content

how this Ternary Operator work with this statemnt?

i just generate this methode to find max val in some matrix and somehowe i was able to change int val insdie Ternary Operator (java 8)

int  max=0, indexToReturn=0;
        int size= arr[0].length;
        for (int i=1 ; i < size ; i++)
            //                                                 ¯_(ツ)_/¯
            max =  (!(arr[j][indexToReturn] > arr[j][i])) ? indexToReturn= i : arr[j][indexToReturn] ;
     return max > 0 ||  indexToReturn==size-1 ? arr[j][indexToReturn] : null;

(the method compile and working)

im not realy sure evan how its compile from what i saw online Ternary Operator syntax :

variable = Expression1 ? Expression2: Expression3

can someone explain me what im missing here ?



The reason this works is because an assignment is an expression. The value of an assignment is the value assigned. This sounds theoretical, so let us look at an example:

int i, k;
i = (k = 5);

Ideone demo

The value of the expression k = 5 is the assigned value 5. This value is then assigned to i.

Armed with this knowledge, we see that indexToReturn= i is an expression that evaluates to the value of i. When we swap Expression2 and Expression3, the ternary operator breaks because the = i is not evaluated as part of the ternary operator (due to operator precedence). If we set parentheses around Expression2, it works as expected.

I would discourage using the fact that an assignment is an expression. (Ab)using this fact often leads to hard-to-understand code.