CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
Basic skills
Order of preference

The order of precedence for arithmetic operations

  1. Increment and decrement
  2. Positive and negative
  3. Multiplication, division, and remainder
  4. Addition and subtraction

How to work with the order of precedence

  • Unless parentheses are used, the operations in an expression take place from left to right in the order of precedence.
  • To specify the sequence of operations, you can use parentheses.
  • When you use an increment or decrement operator as a prefix to a variable, the variable is incremented or decremented and then the result is assigned.
  • When you use an increment or decrement operator as a postfix to a variable, the result is assigned and then the variable is incremented or decremented.

Example 1: A calculation that uses the default order of precedence

double discountPercent = .2; // 20% discount
double price = 100; // $100 price
price = price * 1 - discountPercent; // price = $99.8

The same calculation with parentheses that specify the order of precedence

price = price * (1 - discountPercent); // price = $80

Example 2: An investment calculation based on a monthly investment and yearly interest rate

double currentValue = 5000; // current value of investment account
double monthlyInvestment = 100; // amount added each month
double interestRate = .12; // yearly interest rate
currentValue = (currentValue + monthlyInvestment) * (1 + (interestRate/12)); // currentValue = 5100 * 1.01 = 5151

Another way to calculate the current value of the investment account

currentValue += monthlyInvestment; // add investment
// calculate interest
double monthlyInterest = currentValue * interestRate / 12;
currentValue += monthlyInterest; // add interest

Example 3: Prefixed and postfixed increment and decrement operators

int a = 5;
int b = 5;
int y = ++a; // a = 6, y = 6
int z = b++; // b = 6, z = 5
Previous | Primitive data types | Variables | Constants | Assignment statements and arithmetic expressions | Order of preference | Casting | Next