JMU
Arithmetic Operators
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Going Further: Operator Notations
Going Further: Operator Notations (cont.)
Arithmetic Operators
Binary Arithmetic Operators in Java
Binary Arithmetic Operators in Java (cont.)
Examples in Assignment Statements
  double   area, price;
  int      perimeter;

  area = 12.0 * 15.0;

  price = 45.00 / 2.0;

  perimeter = (300 * 2) + (160 * 2);
  

Review:
Can you identify all of the statements?
Can you identify all of the expressions? (Be careful!)

Binary Arithmetic Operators in Java (cont.)
Integer Division and Remainders
Integer Division and Remainders (cont.)
Going Further: Integer Division and Remainders (cont.)
Going Further: Integer Division and Remainders (cont.)
Unary Numeric Arithmetic Operators in Java
Unary Arithmetic Operators in Java (cont.)
Examples of Arithmetic and Assignment Operators
  int      age, grade, penalty;

  age = +21;
  ++age;

  penalty = -20;
  grade = 100 + penalty;
  
Precedence and Associativity
Precedence in Java (from High to Low)
Associativity in Java
Precedence/Associativity in Java

Gaining Experience

5 + 3 * 2

2 * 4 - 1

2 * (4 - 1)

2 + 8 + 3 - 2

8 * 4 * 2

8 / 4 / 2

A Good Practice
A Good Practice (cont.)
Examples
   double speed, distance, time;
   int    area, width;
   int    elapsed, hours, seconds;


//   mi/hr      mi       hr
   speed  = distance / time;

//  in^2    in      in
   area = width * width;

//   hr        sec     sec/hr
   hours   = elapsed / 3600;

//   sec       sec     sec/hr
   seconds = elapsed % 3600;
  
A Practice to Avoid Revisited
A Similar Example