One category of operators is arithmetic operators. They are used to perform a simple arithmetic operation on primitive data types. There are 5 arithmetic operators in Java which are listed in Table 1.
Arithmetic Symbol | Arithmetic Operation | Numerical Example | Variable Example |
+ | Addition | 1 + 2 | x + y |
– | Subtraction | 5.4 – 1.2 | x – y |
* | Multiplication | 3 * 8 | x * y |
/ | Division | 8 / 4 | x / y |
% | Modulo | 8 % 2 | x % y |
Examples
The following code will output calculate x + y and store the result in an int variable called “result”. The out put will be x + y = 3
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x + y;
System.out.println("x + y = " + result);
}
}
If we do not need to reuse the summation value, we do not have to store it in the result. Alternatively, we can directly add the result of x + y in the println(). The following code will generate the output “x + y = 3”
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x + y;
System.out.println("x + y = " + (x + y));
}
}
Note that in the previous example, we added x + y in parenthesis. This is to give it importance (precedence) over the ‘+’ that refers to concatenation. The example code below will generate the output x + y = 12
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x + y;
System.out.println("x + y = " + x + y);
}
}
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x - y;
System.out.println("x - y = " + result);
}
}
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x / y;
System.out.println("x / y = " + result);
}
}
public class Main{
public static void main(String[] args) {
double x = 1;
double y = 2;
double result = x / y;
System.out.println("x / y = " + result);
}
}
public class Main{
public static void main(String[] args) {
int x = 1;
int y = 2;
int result = x * y;
System.out.println("x * y = " + result);
}
}