Operator precedence in Java - java

In one example from http://leepoint.net/notes-java/data/expressions/precedence.html
The following expression
1 + 2 - 3 * 4 / 5
Is evaluated as
1 + 2 - 3 * 4 / 5
= (1 + 2) - ((3 * 4) / 5)
= 3 - (12/5)
= 3 - 2 The result of the integer division, 12/5, is 2 .
= 1
Then i saw another example from http://www.roseindia.net/java/master-java/operator-precedence.shtml
The following expression
4 + 5 * 6 / 3
is evaluated as
4 + (5 * (6 / 3))
I am slightly confused as to how it is decided which will be evaluated first when * and / are involved. In the examples above, both seem to be difference.
The first example is evaluating 3*5/5 as ((3*4)/5)
Whereas the second example is evaluating 5*6/3 as (5*(6/3))
I know that * and / have precedence over + and - but what about when the expression includes both * and /. And also why are the above two examples showing different approaches? Is one of them wrong?
Edit
public class ZiggyTest {
public static void main(String[] args) {
System.out.println(4 + (5 * (6 / 3)));
System.out.println(4 + ((5 * 6) / 3));
System.out.println(1 + 2 - (3 * (4 / 5)));
System.out.println(1 + 2 - ((3 * 4) / 5));
}
}
The above program produces the output
14
14
3
1
Why are the last two outputs not the same if the first produced the same output.

I am slightly confused as to how it is decided which will be evaluated first when * and / are involved
That's why we have specifications :)
Section 15.7 is the section of the Java Language Specification which deals with evaluation order, and section 15.17 states:
The operators *, /, and % are called the multiplicative operators. They have the same precedence and are syntactically left-associative (they group left-to-right).
So whenever there is A op1 B op2 C and both op1 and op2 are *, / or % it's equivalent to
(A op1 B) op2 C
Or to put it another way - the second linked article is plain wrong in their example. Here's an example to prove it:
int x = Integer.MAX_VALUE / 2;
System.out.println(x * 3 / 3);
System.out.println((x * 3) / 3);
System.out.println(x * (3 / 3));
Output:
-357913942
-357913942
1073741823
That shows the multiplication happening first (leading to integer overflow) rather than the division (which would end up with a multiplication of 1).

Are you sure?
4 + (5 * 6) / 3
4 + 30 / 3
4 + 10
14
4 + 5 * (6 / 3)
4 + 5 * 2
4 + 10
14
They produce the same output because adding the parentheses don't happen to change the result. For your other equation, the parentheses actually do change the result. By removing the parentheses in the equations I solved, the correct path to the result is the first one.

The second one is wrong. See Jon Skeet's answer. Multiplicative operators evaluate left to right. The grouping for:
4 + 5 * 6 / 3
should be
4 + ((5 * 6) / 3).
In this case, though, the wrong grouping
4 + (5 * (6 / 3))
yields the same answer.

Related

unexpected output, confusion between float and integer [duplicate]

This question already has answers here:
Dividing two integers in Java gives me 0 or 100?
(5 answers)
Closed 2 years ago.
I have two statements in java:
System.out.println(2 * (5 / 2 + 5 / 2 ));
This generate the output 8 but again in next line:
System.out.println(2 * 5 / 2 + 2 * 5 / 2 );
This generate the output 10.
now my confusion is why it generates different output
please someone describe it. thanks
Note, that division between ints generates an int (rounded down).
2 * (5 / 2 + 5 / 2) => 2 * (2 + 2) => 8
2 * 5 / 2 + 2 * 5 / 2 => 10 / 2 + 10 / 2 => 10
To get the exact value, you would have to use floats:
2 * (5.0 / 2 + 5.0 / 2) == 10

Android Math Calculation Not Giving Expected Value

I'm trying to run a calculation but I'm not getting the correct result and struggling to understand why.
Calculation
float Signal = ((20 - 0) / (20 - 4)) * (F5 - 4) + 0;
F5 = 12 and is declared as a "Float" type
When run through a calculator, you end up with the following:
((20 - 0) / (20 - 4)) * (12 - 4) + 0
((20) / (16)) * (12 - 4) + 0
(1.25) * (8) + 0
Result = 10
However, when this is run through the Android code, I get the result of 8.
Why is this, I'd like to understand what's going on
The first term ((20 - 0) / (20 - 4)) is calculated using integer arithmetic, giving a value of 1. This makes the final result 8 regardless of the type of F5. If you want it to happen in floating point, use floating point constants
float Signal = ((20f - 0f) / (20f - 4f)) * (F5 - 4f) + 0f;
Technically you don't need all the constants to be floats due to numeric promotion, but it is much clearer to those reading your code that you intended for everything to be a float.

Java post-increment and pre increment behaviour

I have a simple Java expression depicted below. Based on Operator Precedence table, I expect that this expression would return division by zero exception (since post-fix increment operator has highest priority) and expect that resulting expression would look like:
2 + 2 + 5 / 0
But result is 7, why ? (By little bit of experimentation I found that all operators are assigned value of 1 for some reason, but this does not make sense to me in case priority table is correct)
int intCountOperator = 0;
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
System.out.println(unaryOperand); // Prints 7
The operator precedence does not control the evaluation order. It controls only how the expression is to be read. For example, since multiplication has a higher precedence than addition, x + y * z is read as x + (y * z), not (x + y) * z. However, it does not change that first x is evaluated, then y and finally z.
Giving a good example with ++ and -- is more difficult, because there is usually only one reading which makes sense. However, you might notice that y - x++ compiles without error (if x and y are numerical variables). If ++ would have had a lower precedence than - it would be evaluated as (x - y)++ which would not compile.
Because of operator precedence, your expression is evaluated as:
(++intCountOperator) + (intCountOperator + (5 / (intCountOperator++)));
but the evaluation order is not changed by it.
The expression is evaluated from left to right :
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
1 + 1 + 5 / 1 = 7
Note that the operators are evaluated in the order you expect, i.e. 1 + 1 + (5/1) = 1 + 1 + 5 = 7, but the operands of all those expressions are evaluated from left to right.
The order of evaluation is from left to right and not right to left. So the result 7 which you are getting is correct.
unaryOperand = ++intCountOperator + intCountOperator + 5 / intCountOperator++;
is actually
unaryOperand = 1 + 1 + 5 / 1; = 7

Regular expression for arithmetic expression

I,m trying to write a regex to check if the given string is like
a + b, 2 + a + b, 3 + 6 * 9 + 6 * 5 + a * b, etc...
Only + and * operators.
I tried
if (str.matches("(\\d|\\w \\+|\\*){1,} \\d|\\w"))
Unfortunately it only handles cases like 3 * 7 ... (numeric * numeric).
Waiting for your answers, thanks for reading me.
Put * and + inside a character class.
str.matches("\\w(?:\\s[+*]\\s\\w)+");
DEMO
This will handle cases of simple and chained calculations
[0-9A-Za-a]*( ){0,}([+-/*]( ){0,}[0-9A-Za-a]*( ){0,})*
This would match, for example
1+2
1 + 2
1 + a * 14 / 9
(You can change the operators you want by updating [+-/*])

How do math equations work in Java?

When I do something like this
int test = 5 + 3 * (4 - 1) / 2;
I get 9. I suspected this was because int rounds down. However, when I do this
float test = 5 + 3 * (4 - 1) / 2;
I also get 9. However, when I do this
float test1 = 5;
float test2 = 4.5;
float test = test1 + test2;
Test finally outputs 9.5. Could someone explain the logic behind this? Why don't I get 9.5 in the second example? Thanks.
In your second example, although you are assigning the result to a variable of type float, the calculation itself is still performed exactly the same way as the first example. Java does not look at the destination variable type to determine how to calculate the right hand side. In particular, the subexpression 3 * (4 - 1) / 2 results in 4.
To fix this, you can use floating point literals instead of all integers:
float test = 5 + 3 * (4 - 1) / 2.0f;
Using 2.0f triggers floating point calculations for the arithmetic expression.
Although you represent the result of 5 + 3 * (4 - 1) / 2 in a float, the actual evaluation is done with the precision of an integer, meaning that the division of 9 / 2 returns 4 rather than the 4.5 you would receive if they were evaluated as floats.
Expressions have their own type. So start with:
5 + 3 * (4 - 1) / 2
Each value has its own type. This type happens to be int, so this is the same as:
((int)5) + ((int)3) * (((int)4) - ((int)1)) / ((int)2)
Making it clearer that we're dealing with ints. Only after this is evaluated as 9 does it get assigned to a float.
The short answer is that integer types operate on modular arithmetic, with modulus 1, and discard the remainder.
Since you cast test as an integer, modular arithmetic is employed with modulus 1 (e.g. 9.5 mod 1),
int test = 5 + 3 * (4 - 1) / 2;
With a 32-or-64 bit float this would give 9.5; however, because you have cast test as an int, the remainder is discarded, and the value referenced by test is 9.

Categories