06.09.2021 Views

Java with BlueJ, 2016a

Java with BlueJ, 2016a

Java with BlueJ, 2016a

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

30 CHAPTER 2. BASICS<br />

Operator Priorities<br />

Highest to Lowest<br />

* / %<br />

+ -<br />

Multiplication is given the same priority as division and modulo, and addition<br />

is given the same priority as subtraction. However, the priority of<br />

multiplication, division, and modulo is higher than that of addition and<br />

subtraction. The following table shows expressions, the order of evaluation<br />

shown <strong>with</strong> equivalent sub-expressions, and the final result.<br />

<strong>Java</strong> expressions involving priorities<br />

expression equivalent evaluation final result<br />

9.0 / 5.0 + 32.0 (9.0 / 5.0)+ 32.0 33.8<br />

105 - 105 % 10 105 - (105 % 10) 100<br />

1 + 3 * 2 1 + (3 * 2) 7<br />

The next two examples show situations where operator priorities must be<br />

overridden in order to have correct calculations:<br />

Example: Calculate Net Pay<br />

Suppose we must calculate an employee’s net pay. Suppose for the employee<br />

we have their gross pay, deductions from gross, and their tax rate in variables<br />

named grossPay, deductions, andtaxRate respectively. Suppose net pay<br />

is calculated by subtracting deductions from gross pay and then multiplying<br />

bythetaxrate.Ifwecodethisas<br />

grossPay - deductions * taxRate<br />

we will get the wrong result since * has higher priority than -. Wecancode<br />

this using a sub-expression as:<br />

(grossPay - deductions)* taxRate

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!