Showing posts with label Operator Precedence. Show all posts
Showing posts with label Operator Precedence. Show all posts

Friday, February 8, 2013

Week-2: 2.4 : Operator Precedence

Operator Precedence:
You can, of course, calculate using more than two numbers in Java. But you need to take care of
what exactly is being calculated. Take the following as an example:
first_number = 100;
second_number = 75;
third_number = 25;
answer = first_number - second_number + third_number;

If you did the calculation left to right it would be 100 - 75, which is 25. Then add the third
number, which is 25. The total would be 50. However, what if you didn't mean that? What if
you wanted to add the second and third numbers together, and then deduct the total from the first
number? So 75 + 25, which is 100. Then deduct that from the first number, which is 100. The
total would now be 0.

To ensure that Java is doing what you want, you can use round brackets. So the first calculation
would be:

answer = (first_number - second_number) + third_number;

 Details Operator Precedence