Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ternary operator precedence ? Different outputs given

I have the below code producing this output (no space after -1) ==> "1 3 -14 -15 -1"

int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE};
for (int dist : arr) {
    System.out.print((dist == Integer.MAX_VALUE) ? -1 : dist + " ");
}

But if I evaluate the ternary expression separately (as shown below), it gives a different output (what I expected) ==> "1 3 -1 4 -1 5 -1"

int [] arr = {1, 3, Integer.MAX_VALUE, 4, Integer.MAX_VALUE, 5, Integer.MAX_VALUE}; 
for (int dist : arr) {
    int finalDist = (dist == Integer.MAX_VALUE) ? -1 : dist;
    System.out.print(finalDist + " ");          
}

What is going wrong with the first code snippet?

like image 287
bighi Avatar asked Jun 24 '26 19:06

bighi


1 Answers

Here

(dist == Integer.MAX_VALUE) ? -1 : dist + " "

The space will be added only if the condition is false. You should use parantheses to add " " at all times like below.

((dist == Integer.MAX_VALUE) ? -1 : dist) + " "

The ternary operator has only operator precedence over the assignment operators. (See below)


Oracle Site about Operator Precedence

The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence.

enter image description here

like image 183
Yassin Hajaj Avatar answered Jun 26 '26 10:06

Yassin Hajaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!