# Java - Arithmetic Operators

Java

Share In this tutorial we will learn about arithmetic operators in Java programming language.

Java programming language provides us with all the basic arithmetic operators.

Operator Description
- Subtraction or unary minus
* Multiplication
/ Division
% Modulo division

In the following example we will add two integer numbers using the addition operator.

``````class Arithmetic {
public static void main (String args[]) {
int a = 10;
int b = 20;
int sum = a + b;
System.out.println("Result: " + sum);
}
}
``````

Output:

``````Result: 30
``````

## Subtraction Operator

In the following example we will subtract two integer numbers using the subtraction operator.

``````class Arithmetic {
public static void main (String args[]) {
int a = 10;
int b = 20;
int diff = a - b;
System.out.println("Result: " + diff);
}
}
``````

Output:

``````Result: -10
``````

## Multiplication Operator

In the following example we will multiply two integer numbers using the multiplication operator.

``````class Arithmetic {
public static void main (String args[]) {
int a = 10;
int b = 20;
int prod = a * b;
System.out.println("Result: " + prod);
}
}
``````

Output:

``````Result: 200
``````

## Division Operator

In the following example we will divide two integer numbers using the division operator.

``````class Arithmetic {
public static void main (String args[]) {
int a = 10;
int b = 20;
int div = a / b;
System.out.println("Result: " + div);
}
}
``````

Output:

``````Result: 0
``````

Note! We are getting 0 because type `int` can only hold integer values so, the result is getting truncated. To get the correct result we have to use floating point types like `float` or `double`.

``````class Arithmetic {
public static void main (String args[]) {
int a = 10;
int b = 20;
float div = (float) a / b;
System.out.println("Result: " + div);
}
}
``````

We are type casting variable a to float by writing `(float) a`.

Output:

``````Result: 0.5
``````

## Modulus Operator

In the following example we will find the remainder when dividing two integer numbers using the modulus operator.

``````class Arithmetic {
public static void main (String args[]) {
int a = 5;
int b = 2;
int mod = a % b;
System.out.println("Result: " + mod);
}
}
``````

Output:

``````Result: 1
``````

We get 1 because on dividing 5 by 2 we get remainder 1.

Share