The following expression evaluates to 14.
int a=4;
int b=6;
int c=1;
int ans= ++c + b % a - (c - b * c);
System.out.print(ans);
This is how i calculate this
1. (c - b * c) // since bracket has highest preference
ans : -5
2. ++c //since unary operator has next highest preference
ans : 2
3. b%a // % has higher preference than + and -
ans : 2
Therefore, 2 + 2 - (-5) = 9
As you can see I'm getting 9 as the value. Not sure what's wrong in my way of calculation (pretty sure I'm gonna end up looking stupid)
Edit : I refered to the below link for precedence and association.
https://introcs.cs.princeton.edu/java/11precedence/
Can someone explain the difference between level 16 and level 13 parentheses? I thought level 13 parentheses is used only for typecasting. That is why i considered level 16 parenthesis for evaluating the expression.
Evaluation order is not the same as precedence. Java always evaluates left-to-right (with a minor caveat around array accesses).
Effectively, you are evaluating the following expression, because the very first thing that happens is the pre-increment of c:
2 + 6 % 4 - (2 - 6 * 2)
Precedence then describes how the values are combined.
As you are using pre-increment operator on c. So, after applying increment on c the value of c will be 2. Now :
(c - b * c) will be evaluated to (2 - 6 * 2)= -10
So, the final expression will be 2 + 2 - (-10) = 14
Related
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
I am java newbie and trying to understand how calculation steps are performed to achieve final result. The final answer is coming as 49. Looking at precedence operators hierarchy my calculation is not coming to 49.
Following is my code with expression:
class Test
{
public static void main(String args[])
{
int a = 6, b = 5;
a = a + a++ % b++ *a + b++ * --b;
System.out.print(a)
}
}
Modulo has same precedence as division and multiplication. The next precedence goes to addition and subtraction.Operations happen left to right.
Adding brackets for better clarity:
( a ) + ( a++ % b++ *a ) + ( b++ * --b )
group I II III
a++ % b++ *a evaluated as :a. (6 % 5) = 1
b. 1 * 6 till now, a = 6, b = 5
Having completed this operation, the value of a & b are incremented to 7 & 6 respectively. i.e the post fix increment happens only after the modulo/multiplication/division during a step or group as shown above.
b++ * --b => 6 * 6. gives value of 36
Having completed this operation the ++ operation is performed but -- is also performed, effectively leaving the value of b at 6.
next operation is addition. i.e 7 + 6 + 36 = 49
Reference: https://www.programiz.com/java-programming/operator-precedence
Operators have priorities. There is a table of these here.
Also, you can use round brackets (parentheses) for forcing the right sequence of calculations.
When an expression has two operators with the same precedence, the expression is evaluated according to its associativity. I want to know how the following works:
i=b + b + ++b
i here is 4
So ++b didn't change the first 2 b values, but it executed first, because the execution is from left to right.
Here, however:
int b=1;
i= b+ ++b + ++b ;
i is 6
According to associativity, we should execute the 3rd b so it should be:
1+ (++1) + ( ++1 should be done first). so it becomes:
1 + ++1 + 2 =5
However, this is not right, so how does this work?
You are confusing precedence with order of execution.
Example:
a[b] += b += c * d + e * f * g
Precedence rules state that * comes before + comes before +=. Associativity rules (which are part of precedence rules) state that * is left-associative and += is right-associative.
Precedence/associativity rules basically define the application of implicit parenthesis, converting the above expression into:
a[b] += ( b += ( (c * d) + ((e * f) * g) ) )
However, this expression is still evaluated left-to-right.
This means that the index value of b in the expression a[b] will use the value of b from before the b += ... is executed.
For a more complicated example, mixing ++ and += operators, see the question Incrementor logic, and the detailed answer of how it works.
It's correct, first b is 1, and the second b will be incremented by 1 before addition, so it's 2, and the third b is already 2, and incremented by 1 makes it 3. so It's 6 in total. The expression is evaluated from left to right as you said, thus the third b is already 2 before increment.
What is the correct sequence of the math operations in this expression in Java:
a + b * c / ( d - e )
1. 4 1 3 2
2. 4 2 3 1
I understand that result is the same in both answers. But I would like to fully understand the java compiler logic. What is executed first in this example - multiplication or the expression in parentheses? A link to the documentation that covers that would be helpful.
UPDATE: Thank you guys for the answers. Most of you write that the expression in parentheses is evaluated first. After looking at the references provided by Grodriguez I created little tests:
int i = 2;
System.out.println(i * (i=3)); // prints '6'
int j = 2;
System.out.println((j=3) * j); // prints '9'
Could anybody explain why these tests produce different results? If the expression in parentheses is evaluated the first I would expect the same result - 9.
Almost everybody so far has confused order of evaluation with operator precedence. In Java the precedence rules make the expression equivalent to the following:
a + (b * c) / ( d - e )
because * and / have equal precedence and are left associative.
The order of evaluation is strictly defined as left hand operand first, then right, then operation (except for || and &&). So the order of evaluation is:
a
b
c
*
d
e
-
/
+
order of evaluation goes down the page. Indentation reflects the structure of the syntax tree
Edit
In response to Grodriguez's comments. The following program:
public class Precedence
{
private static int a()
{
System.out.println("a");
return 1;
}
private static int b()
{
System.out.println("b");
return 2;
}
private static int c()
{
System.out.println("c");
return 3;
}
private static int d()
{
System.out.println("d");
return 4;
}
private static int e()
{
System.out.println("e");
return 5;
}
public static void main(String[] args)
{
int x = a() + b() * c() / (d() - e());
System.out.println(x);
}
}
Produces the output
a
b
c
d
e
-5
which clearly shows the multiplication is performed before the subtraction.
As JeremyP has nicely shown us, the first answer is correct.
In general, the following rules apply:
Every operand of an operator is evaluated before the operation itself is performed (except for ||, &&, and ? :)
Operands are evaluated left to right. The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated.
The order of evaluation respects parentheses and operator precedence:
Parentheses are evaluated first.
Operators are evaluated in order of precedence.
Operators with equal precedence are evaluated left-to-right, except for assignment operators which are evaluated right-to-left.
Note that the first two rules explain the result in your second question:
int i = 2;
System.out.println(i * (i=3)); // prints '6'
int j = 2;
System.out.println((j=3) * j); // prints '9'
Reference documentation:
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#4779
Tutorial:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
It evaluates the expressions in the following order. Variable names are expressions that need to be evaluated.
a + b * c / (d - e)
2 3 5 6
4 7
1 8
9
So, the answer to your question is #1. The order of operations determines the shape of the expression tree (what is the left side of the tree, and what is the right), but the left side is always evaluated first (and the root is evaluated last).
I would imagine that it might evaluate something like this evaluating from left to right.
a+b*c/(d-e)
Action Left Value Right Value
Start Add a b*c/(d-e)
Start Multiply b c
Calc Multiply (since it can)
Start Divide b*c (d-e)
Start Subtract d e
Calc Subtract
Calc Divide
Calc Add
This can be thought of as creating a binary tree representing the calculations and then working from the leaf nodes, left to right, calculating things. Unfortunately my ascii art isn't great but here's an attempt at representing the tree in question:
Add
/\
/ \
a \
Divide
/ \
/ \
/ \
/ \
Multiply Subtract
/\ /\
/ \ / \
b c d e
And I did some tests in C# (I know its not the same but that's where my interests lie and the tests can be easily adapted) as follows:
f = 1;
Console.WriteLine((f=2) + (f) * (f) / ((f) - (f)-1));
Console.WriteLine(2 + 2 * 2 / (2 - 2 - 1));
f = 1;
Console.WriteLine((f) + (f=2) * (f) / ((f) - (f)-1));
Console.WriteLine(1 + 2 * 2 / (2 - 2 - 1));
f = 1;
Console.WriteLine((f) + (f) * (f = 2) / ((f) - (f)-1));
Console.WriteLine(1 + 1 * 2 / (2 - 2 - 1));
f = 1;
Console.WriteLine((f) + (f) * (f) / ((f=2) - (f)-1));
Console.WriteLine(1 + 1 * 1 / (2 - 2 - 1));
f = 1;
Console.WriteLine((f) + (f) * (f) / ((f) - (f=2)-1));
Console.WriteLine(1d + 1d * 1d / (1d - 2d - 1d));
The pairs of console.writeline statements are the algebraic one (using the set a number trick) and a numerical representation showing what the calculation actually does. The pairs produce the same result as each other.
As can be seen the arguments are evaluated in order with any after the assignment being 2 and those before being one. So the order of evaluation of things is simple left to right I think but the order of calculations is as you would expect it to be.
I assume this can be run almost with copy and paste to test in JAVA...
There may be some unnoticed assumptions in here so if anybody does spot logic flaws in here please do call me on them and I'll work them through.
i am assuming that your expression would be something like
x = a + b * c / ( d - e )
the equality operator has right to left order of evaluation. so the expression on the right of = will be evaluated first.
if your refer this precedence chart: http://www.java-tips.org/java-se-tips/java.lang/what-is-java-operator-precedence.html
1) the brackets will be evaluated (d-e), lets say (d - e) = f so the expression then becomes
x = a + b * c / f.
2) Now * and / have same precedence, but the order of evaluation is left to right to * will be evaluated first so lets say b * c = g, so the expression becomes x = a + g /f
3) Now / has the next precedence so g / f will be evaluated to lets say h so the expression will be come x = a + h,
4) lastly evaluating a + h
In your second question, it seems Java is evaluating the part in parenthesis as an assignment, not an mathematical expression. This means that is will not perform parenthetical assignments in the same order as operations in parenthesis.
The results of the calculation are defined by the Operator Order of Precedence. So parentheses have highest precedence here, multiplication and division next highest, and addition and subtraction lowest. Operators with equal precedence are evaluated left to right. So the expression in the question is equivalent to:
a + (b * c) / ( d - e ))
However there is a slight difference between what is normally meant by "being evaluated first" and the operator precedence for getting the correct answer.
"d-e" is not necessarily actually calculated before "a" is calculated. This pretty much doesn't make any difference unless one of the 'variables' in the expression is actually a function. The Java standard does not specify the order of evaluation of components of an expression.
a + b * c / ( d - e )
1 1
2
3
The whole point of operator precedence is to convert the expression into a syntax tree. Here the * and - are at the same level of the tree. Which one is evaluated first is irrelevant for the result and not warrantied.
Edit: Sorry, I got confused by my C background. As others have pointed out, Java has an "Evaluate Left-Hand Operand First" rule. Applying this rule to / tells you that * is evaluated first (your first answer).
This might seem simple but it's just stumbled me and my friends...
lets take the following piece of code-
in java
//........
int a=10;
a= a-- + a--;
System.out.print("a="+a);
//........
in c
//........
int a=10;
a= a-- + a--;
printf("a= %d",a);
//.......
where in the former case you get output as 19 in C you get it as 18.
the logic in c is understandable but in java?
in java if its like
int a=10;
a=a++;
in this case the output is 10.
So what's the logic?
a = a-- + a-- causes undefined behaviour in C. C does not define which decrement should be evaluated first.
a-- evaluates to the value of a, and after that it decrements a,
so in Java a = a-- + a-- evaluates like this:
a = (10, decrement a) + (9, decrement a)
The second operand is 9 because first term caused a to be decremented.
In summary: With that expression, C does not define the evaluation order. Java defines it to be from left to right.
I don't know about Java but in C that line of code doesn't have a return value defined in the standard. Compilers are free to interpret it as they please.
In the expression
a = a-- + a--;
you have a lot of sub-expressions that need to be evaluated before the whole of the expression is evaluated.
a = a-- + a--;
^^^ <= sub-expression 2
^^^ <= sub-expression 1
What's the value of sub-expression 1? It's the current value of the object a.
What's the value of the object a?
If the sub-expression 2 was already evaluated, value of object a is 9, otherwise it is 10.
Same thing for sub-expression 2. Its value can be either 9 or 10, depending on whether sub-expression 1 was already evaluated.
The C compiler (don't know about Java) is free to evaluate the sub-expressions in any order
So let's say the compiler chose to leave the --s for last
a = 10 + 10;
a--; /* 19 */
a--; /* 18 */
but on the next compilation the compiler did the --s up front
/* value of sub-expression 1 is 10 */
/* value of sub-expression 2 is 9 */
a = 10 + 9; /* a = 9 + 10; */
or it could even save one of the a-- and use that for the final value of a
/* sub-expression 1 yields 10 and sets the value of `a` to 9 */
/* so yield that 10, but save the value for the end */
a = 10 + ???;
a = 18???; a = 19???;
/* remember the saved value */
a = 9
Or, as you invoked undefined behaviour, it could simply replace your statement with any of the following
a = 42;
/* */
fprintf(stderr, "BANG!");
system("format C:");
for (p=0; p<MEMORY_SIZE; p++) *p = 0;
etc ...
You are post-decrementing. To me, the java result makes more sense.
The first a-- is evaluated as 10, and decrements to 9. 10 is the value of this sub-expression.
The second a-- is evaluated. a is now 9, and decrements to 8. The value of this sub-expression is 9.
So, it becomes 10 + 9 = 19. The two decrements get overwritten by the assignment.
I'd expect 18 if the expression were a= --a + --a.
Have you tried compiling the C version with different optimization flags?
a= a-- + a--;
This invokes undefined behaviour in C/C++. You should not expect consistent results from this statement.
a = 10 + 9
you can try with:
a = a-- + a-- + a--
it returns 27 ( 10 + 9 + 8)...