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 SymbolArithmetic OperationNumerical ExampleVariable Example
+Addition1 + 2x + y
Subtraction5.4 – 1.2x – y
*Multiplication3 * 8x * y
/Division8 / 4x / y
%Modulo8 % 2x % y
Table 1 – List of Arithmetic Operators

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);
    }
}

Other Lessons in Introduction to Programming in Java

No. Lesson Reading Time
1 Introduction to Java 5 mins
2 Setting up the environment in Java 5 mins
3 Java Hello World Program 5 mins
4 Java Output 5 mins
5 Java Escape Characters 5 mins
6 Variables & Types 5 mins
7 Arithmetic Operators in Java 5 mins

Related Subjects

or view all subjects
No realted subjects found.