1. Arithmetic Operators
Math operators
Addition "+", Subtraction "-", Multiplication "*" and Division "/" may already be familiar to you. Like in math, multiplication and division are performed before addition and subtraction. In addition, you can use parenthesis to force order.
Integers truncate during division, just like when you cast from double to int. Thus, 5/2 is 2, not 2.5 nor 3.
public class MyProgram { public static void main(String[] args) { int x = 5 ; System.out.println(x/ 2 ); //prints 2 System.out.println(x/ 2.0 ); //prints 2.5, Java autocasts System.out.println(x+ 4 / 2 ); //prints 5+2 or 7 System.out.println(x+ 2 * 5 ); //prints 10 double y = 5.0 ; System.out.println(y/ 2 ); //prints 2.5 System.out.println(y- 2 ); //prints 3.0 System.out.println(x*y+x/(y- 4 )); //prints 25.0+5.0 or 30.0 } } |
The modulo operator
The % operator is pronounced "modulo" or "mod", and it performs remainder. For example, 10 % 3 is 1, because 10 divided by 3 has a remainder of 1. 13 % 7 is 6. Modulo has the same operator precedence as multiplication and division.
Modulo also works on decimal numbers, and it is a great way to check if two numbers are divisible. If a % b equals zero, then a is divisible by b.