Learn about arithmetic operators in java programming i.e. + plus, – minus, * multiplication, /division and % modulo operators with simple example and explanation.
Below are the arithmetic operators in java language that are used to perform arithmetic operations on primitive data types i.e. int, float and double etc in java.
+ Plus
– Minus/Subtraction
* Multiplication
/ Division
% Modulus or remainder operator
NOTE: Modulus Operator:
Some of the people may not be understanding % modulus operator. So, here is brief about % MODULUS OPERATOR.
The % operator returns the remainder of two numbers. For example, 10 % 4 is 2 because 10 divided by 4 leaves a remainder of 2.
Another example,
5%2 leaves a remainder of 1.
Code Example on arithmetic operators in java
In below java program, two numbers are given 20 and 30 in variables a and b respectively. The program has demonstrated how to perform arithmetic operations using on two numbers using each arithmetic operators’ and output.
public class Sample {
public static void main(String[] args) {
double a = 20;
double b = 10;
System.out.println("first number =" + a);
System.out.println("Second number =" + b);
System.out.println("Arithmetic operations :");
// Addition (+)
double sum = a + b;
System.out.println("\tSum =" + sum);
// Subtraction (-)
double sub = a - b;
System.out.println("\tSub =" + sub);
// Division (/)
double div = a / b;
System.out.println("\tDiv =" + div);
// Multiplication (*)
double multiplication = a * b;
System.out.println("\tMultiplication =" + multiplication);
// Modulo (*)
double module = a % b;
System.out.println("\tModulo =" + module);
}
}
Output:
first number =20.0
Second number =10.0
Arithmetic operations :
Sum =30.0
Sub =10.0
Div =2.0
Multiplication =200.0
Modulo =0.0
More on Arithmetic operators in Java
Arithmetic operators follow the BODMOS Rule that we have already studied in school. That is perform div, then multiplication, then + or – etc.
Java language follows the same.
For example, expression 2+2/2*2 will result into 4.
Java code:
public class Sample {
public static void main(String[] args) {
double result;
result = 2+2/2*2; //Expression
System.out.println("result =" + result);
}
}
Output:
result =4.0