saltandwater saltandwater - 3 months ago 16
Java Question

Parentheses while using ternary operator

Why is the output different for the two cases below? It was part of a bigger problem that I've debugged and narrowed down to the issue

public static void main(String[] args) {

String test = "hello";
System.out.println(call() + test.charAt(0)=='h'?1:0);
}

static int call()
{
return 1;
}



Output : 0


But if I add a paranthesis, I get the expected output

public static void main(String[] args) {

String test = "hello";
System.out.println(call() + (test.charAt(0)=='h'?1:0));
}

static int call()
{
return 1;
}



Output : 2 (as expected)


In the initial call, is call() + test.charAt(0) evaluated against 'h', and assigned 1 and 0 accordingly? Which means {1 + ascii value of 'h'} == 105 is evaluated against ascii value of 'h' which is 104?

Answer

There is actually no problem, the operators have difference precedence order.

If you check the link that Andy Turner added in his comment you will find this table

enter image description here

As you can see the additive (+ and -) has higher precedence over the ternary operator. This is why:

call() + test.charAt(0)=='h'?1:0
^^^^^^^^^^^^^^^^^^^^^^^
  High precedence      
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       Less precedence

So, you can change the precedence order using parentheses:

call() + (test.charAt(0)=='h'?1:0)
          ^^^^^^^^^^^^^^^^^^^^^^^
              High precedence      
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       Less precedence