# Learn Java the Hard Way (Second Edition)

## Exercise 6: Mathematical Operations

Now that we know how to declare and initialize variables in Java, we can do some mathematics with those variables.

### What You Should See

The plus sign (`+`) will add two integers or two doubles together, or one integer and one floating-point value (in either order). With two Strings (like on line 32) it will concatenate5 the two Strings together.

The minus sign (`-`) will subtract one number from another. Just like addition, it works with two integers, two floating-point values, or one integer and one double (in either order).

An asterisk (`*`) is used to represent multiplication. You can also see on line 15 that Java knows about the correct order of operations. b is multiplied by 3 giving `81` and then a is added.

A slash (`/`) is used for division. Notice that when an integer is divided by another integer (like on line 17) the result is also an integer and not floating-point.

The percent sign (`%`) is used to mean ‘modulus’, which is essentially the remainder left over after dividing. On line 19, b is divided by `10` and the remainder (`7`) is stored into the variable g.

Modular arithmetic is a fairly simple mathematical operation that just isn’t often taught in public school or even introductory university math curriculum. Wikipedia’s example is good enough: we do modular arithmetic every time we add times on a typical 12-hour clock. If it is 7 o’clock now, what time will it be in eight hours? Well, once we hit 12:00 we “wrap around”, so it will be 3 o’clock. (8+7 = 15, 15-12 = 3)

Put another way, 15 divided by 12 is 1 with a remainder of 3.

Modular arithmetic is used more than you would think in programming, but I won’t be using it too much in the book.

Footnotes:

“Learn Java the Hard Way” is ©2013–2016 Graham Mitchell