In: Computer Science
Explain how Java resolves the ambiguity of the statement var d = a - b - c;
Answer:-
Here, the given statement is
var d = a-b-c
In this statement, we have a single operator two times. So we can say that we have two operators with the same priority. Therefore we will have to understand the associativity rule for these operators to be resolved.
Java follows left to right associativity for additive operators(+,-). This means that it solves the expression from left to right for additive operators of the same priority.
Now we have the given statement as follow
d = a-b-c
So, Java will resolve this expression as below
d = (a-b) - c
First, it will evaluate (a-b) , and then it will subtract the c from the result of (a-b).
For Example:-
Suppose we have
a=3, b=4, c=5
So the given expression will be evaluated as below
d = (3-4) - 5
d = (-1) - 5
d = -6
So, the final value of d will be -6.
NOTE:- I have included a screenshot of a Java program, so it can help you to understand easily.
JAVA CODE:-
OUTPUT:-
I hope, it would help.
Thanks!