Sunday, July 27, 2014

Java Basics 104 - Operator Precedence

---
Java Basics 104 – Operator Precedence

STEPS

1) Browse http://ideone.com/1gau2Z 

2) Three numbers operation

Change line no. 13 to:
int first_number, second_number, third_number, answer;
Change line no.14-15 to:
first_number = 100;
second_number = 75;
third_number = 25;
Change line no. 16 to:
answer = first_number - second_number + third_number;
Change line no.18 to:
System.out.println("Total = " + answer );
Outcome:
3) Three numbers operation with bracket 1
Change line no. 17 to:
answer = (first_number - second_number) + third_number;
Outcome:
4) Three numbers operation with bracket 2
Change line no. 17 to:
answer = first_number - (second_number + third_number);
Outcome:
5) Three numbers operation with + and *
Change line no. 17 to:
answer = first_number + second_number * third_number;
Outcome:
The following codes also leads to the same outcome:
answer = first_number + (second_number * third_number);
Change the position of the brackets as follows. What would be the outcome?
answer = (first_number + second_number) * third_number;
6) Three numbers operation with () and /
Change line no. 17 as follows. What is the outcome?
answer = first_number + second_number / third_number;
Change line no. 17 as follows. What is the outcome?
answer = (first_number + second_number) / third_number;

LESSONS:

Here's a list on Operator Precedence
  • Multiply and Divide - Treated equally, but have priority over Addition and Subtraction
  • Add and Subtract - Treated equally but have a lower priority than multiplication and division
So if you think Java is giving you the wrong answer, remember that Operator Precedence is important, and add some round brackets.

REFERENCE

---

No comments:

Post a Comment