**Lesson 1.5a - Basic
Math **

Purpose: To learn how to write
statements involving basic arithmetic

Java Math Mathematics plays a large role in computer programming. Practically everything
boils down to math in some way. So Java has to have a way of performing
math operations. We will begin with basic arithmetic: addition,
subtraction, multiplication and division.

Java's Arithmetic
Symbols
operation |
symbol |
example of use |

addition |
+ |
a = b + c; |

subtraction |
- |
a = b - c; |

multiplication |
* |
a = b * c; |

division |
/ |
a = b / c; |

**Order of
Operations** Java has the same order of operations as in
Algebra. Remember **PEMDAS**?

**P**arentheses

**E**xponents

**M**ultiplication and **D**ivision together

**A**ddition and **S**ubtraction together

**Modulus** The *modulus* operator is another arithmetic operation that you will find quite useful.
Modulus, or *mod* for short, gives the **integer remainder** of
division. The symbol for modulus is **%**, but it has nothing to do with
percents. Here are some examples of results of modulus calculations:

**13 % 5 = 3**

**26 % 10 = 6 **

**20 % 4 = 0 **

**5 % 7 = 5 **

Note that modulus is an integer operator. It
does not work with decimal values. So you would never write a calculation
like **5.8 % 3.1**. Modulus works
only with integer *operands* and its result is always an integer.

**Application of
Modulus** OK, *mod* gives the remainder of integer
division. So what? Well, it turns out that mod will be useful in a variety
of situations. One of these situations is breaking a measured value into
different units. For example, suppose we want to break total seconds down
into hours, minutes and seconds. Recall that there are 60 seconds in a
minute and 60 minutes in an hour. That means there are 3600 (60 * 60)
seconds in an hour. So here is how modulus would break 10,000 total
seconds into hours, minutes and seconds.

int totalSeconds = 10000;

int hours = totalSeconds / 3600; // the result is 2

int minutes = totalSeconds % 3600 / 60; // the result is 46

int seconds = totalSeconds % 3600 % 60; // the result is 40

**So 10,000 seconds = 2 hours, 46 minutes and 40 seconds **

Note the pattern of using / then % from each
equation to the next. This pattern will also be used in your programming
problems involving modulus (#'s 6-8). Secondly, recall that when dividing
integers, the result will be an integer. That is why the calculation for
hours and minutes works correctly here.

**In Closing **Remember to work with
only integers when using modulus. It doesn't work with
decimal values. Lastly, modulus falls in with multiplication and division in the order of operations.