The Coder's Handbook
Math
ARITHMETIC OPERATORS
Arithmetic Operators
You can use math functions in Java to modify the values of variables. They follow normal order of operations.
Addition +
Subtraction -
Multiplication *
Division /
Remember that = is the assignment operator. It isn’t saying that two things are equal, or checking the value. It means a very specific thing: the left hand side is given the value of the right hand side. This upsets mathematicians, but that is okay, for they have no power in this place.
We can use math when initializing variables:
int a = 2;
int b = 12;
int c = a * 2 - b; // c is assigned 2 * 2 - 12, which is -8
int d = b / 3 + a; // d is assigned 12 / 3 + 2, which is 6
We can also use math when assigning values to already existing variables:
int a = 2;
int b = 12;
a = a + 5; // a is assigned a new value, 2 + 5, which is 7.
b = b * 2; // b is assigned a new value, 12 * 2, which is 24.
Compound Operators
Each of these operators has a shorthand called a compound operator that allows you to modify a value by a certain amount.
a += 5; // Equivalent to a = a + 5
a -= 5; // Equivalent to a = a - 5
a *= 5; // Equivalent to a = a * 5
a /= 5; // Equivalent to a = a / 5
Increment and Decrement
Finally, there is an even shorter version for addition and subtraction. This allows you to increment or decrement a value by one.
a++; // Equivalent to a = a + 1
a--; // Equivalent to a = a - 1
MATH AND TYPES
Dividing By Zero
If you divide by zero, the world will explode. Okay, maybe not that bad but your program will certainly crash and throw an ArithmeticException.
Integer Division
In the previous entry, you learned how Java is smart enough to detect when you're mixing different types. But what happens if we do division using entirely integers? Consider the following example:
int a = 5;
int b = 2;
System.out.println(a / b);
In this case, we print out the result 2. This is because an integer cannot store the value 2.5, and the value is instead truncated to 2.
MODULUS
Modulus
The modulus operator % returns the remainder of a division.
r = 8 % 5; // 5 goes into 8 once, and has 3 leftover. Thus r = 3;
r = 8 % 3; // 3 goes into 6 twice, and has 2 leftover. Thus r = 2;
r = 8 % 2; // 2 goes into 8 four times, and has 0 leftover. Thus r = 0;
Modulus is useful in a lot of problems. It can be combined with a conditional to check if a number is divisible by another or if it’s odd/even. Modulus is also used to convert things from 24 hour time to 12 hour time.
Remember modulus - it comes up all the time in weird places.
twelveTime = 14 % 12; // 2:00 pm
This is a clock. Like your phone, it is used to tell time. Ironically, it cannot run TikTok.
RESOURCES