Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

variable = Expression1 ? Expression2: Expression3

can someone explain me what im missing here ?

>Solution :

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);
System.out.println(i);
System.out.println(k);

Ideone demo

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

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading