|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Arithmetic Operators in Java
Arithmetic operators are the most widely used operators of the Java language simply because they're used to compute numbers. There are four different arithmetic operators, namely: + (addition) - (subtraction) * (multiplication) / (division) % (modulo) - (unary minus) Arithmetic operators can be used on any primitive data type except for boolean. Here are some examples of how to use them: |
//addition int i = 5, j = 6; System.out.println(i + j); //subtraction float i1 = 5; int j1 = 6; System.out.println(i1 + j1); //multiplication int i2 = 5, j2 = 6; System.out.println(i2 * j2); //division double i3 = 5; int j3 = 6; System.out.println(i3 j3); //modulo int i4 = 15, j4 = 4; System.out.println(i4 % j4); //unary minus int i5 = 5; System.out.println(-i5); |
Modulo returns the remainder when the first operand is divided by the second operand an integral number of times. The unary minus simply converts a positive number to a negative (or a negative number to positive, like -(-5)). It's important to remember that if one of the operands is a floating-point number, floating-point arithmetic will be used. If not then integer arithmetic will be used, so the output of the above code will look like this: |
11 11.0 30 0.8333333333333334 3 -5 |
| Previous | Next | |
Tutorial Home | ||
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
