Introduction to Java : Data Types and Operators Part-4
Operators
Java also provides several operators that you can use to manipulate your variables.
Mathematical Operators
As in all languages, Java allows you to perform math functions. The following table outlines the available functions:
| Operator | Description | Example |
|---|---|---|
| + | Performs addition | int x = 1; int y = 2; int z = x + y // z = 3 |
| – | Performs subtraction | int x = 2; int y = 1; int z = x – y // z = 1 |
| \ * | Performs multiplication | int x = 2; int y = 2; int z = x * y // z = 4 |
| / | Performs division | int x = 4; int y = 2; int z = x / y // z = 2 |
| % | Gets the remainder (modulus) | int x = 6; int y = 4; int z = x % y // z = 2 |
One thing to remember about mathematics in Java is that since variables are typed, you should be careful to match types or expect automatic casting! In other words, Java will return the result in a type that fits in the result regardless of what was used in the equation.