Simple Java Maths
Explore Java's basic math operations, including addition, subtraction, multiplication, division, and modulus. Understand the order of operations (BODMAS) and operator associativity to correctly evaluate expressions and write reliable Java code.
We'll cover the following...
Introduction
Math in Java is very simple. Keep in mind that Java mathematical operations follow a particular order much the same as high school math.
For example, multiplication and division take precedence over addition and subtraction. The order in which these operations are evaluated can be changed using parentheses.
Operations in Java
The arithmetic operators in Java are listed below.
| Symbols | Arithmetic operators |
|---|---|
| + | add |
| - | subtract |
| / | divide |
| * | multiply |
| % | modulus division |
| ++ | post and pre-increment |
| -- | post and pre-decrement |
Example
Let’s take a look at how to use these operations while coding in Java.
Operator precedence
Operator precedence specifies the order in which operations will execute provided that the expression contains more than one operator. With mathematical operations, the precedence follows the rule of BODMAS, which says; Brackets, Order, Division, Multiplication, Addition, and then Subtraction. Let’s look at an example below to check this!
For the purpose of these examples, we will set the following variables; ...