I was trying to execute simple java program to calculate result with expression as: v^2 - u^2 / 2as
that is v*v - u*u / 2*a*s
code is in java 11
int v=16;
int u =5;
int a = 7;
int s = 9;
int res1 = v*v;
int res2 = u*u;
double FunRes1 = Math.pow(v, 2);
double FunRes2 = Math.pow(u, 2);
int part1 = res1 - res2;
int part2 = 2 *a*s;
int result = part1/part2; // = All 4
int AllResult = (v*v-u*u)/2*a*s; // == results
double doubleResult = FunRes1-FunRes2 / 2*a*s; // === have different
double doubleResult2 = (FunRes1-FunRes2) / 2*a*s; // ==== answers (see ss above)
the asnwers of all 4 variable ( result , AllResult , doubleResult1 , doubleResult2 ) are different . Anyone explain why this happen ? and What is the correct answers mathematically ?
This is because of operator precedence. If I write something like 2 * 8 / 8 - 6
, without further context, it is ambiguous how it should be evaluated. This can lead to different results. For example (2 * 8) / (8 - 6) == 8
but ((2 * 8) / 8) - 6 == -4
. To disambiguate, Java uses a list of precedence rules that are common throughout most languages. You can find the complete list here.
For your case the important part is that multiplication and division are applied before addition and subtraction.
Also of note is what happens in the case of operators having equal precedence, which also appears in your example.
When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
Going back to our example of 2 * 8 / 8 - 6
. We can see (from here) that java will evaluate multiplication and division before subtraction. *
and /
have the same precedence and are both binary operators so we evaluate them left to right. This leaves us with ((2 * 8) / 8) - 6
which is why java evaluates this as -4
System.out.println(2 * 8 / 8 - 6);
-4