Java Arithmetic Operators and Examples

Arithmetic operations are one of the most basic functions of programming languages. This article explains how you can perform operations such as addition, subtraction, multiplication and division in Java.

Java Arithmetic Operators and Examples

Example 1: Usage of Addition (+), Subtraction (-),  Multiplication (*) and Division (/)

int a=12;
int b=6;

int sum = a + b; //18
int difference = a - b; //6
int multiplication = a * b; //72
int division = a / b; //2

 

Example 2: Problem with the int/int division

Problem: If you divide an integer to an another integer, the fractional part is cut off.

int a=3;
int b=2;

double division = a / b;
System.out.println(division); // 1.0
//should be 1.5

 

Solution: one of the dividend or divisor is double (or both), problem will be solved. We can use casting for integer variables.

int a=3;
int b=2;

double division1 = (double)a / b;
double division2 = a / (double)b;
double division3 = (double)a / (double)b;

System.out.println(division1); // 1.5
System.out.println(division2); // 1.5
System.out.println(division3); // 1.5

We can also use double variables for divident or divisor.

double a=7;
int b=5;
double c=3;

double division1 = a / b; // double/int
double division2 = a / c; // double/double
double division3 = b / c; // int/double

System.out.println(division1); // 1.4
System.out.println(division2); // 2.3333333333333335
System.out.println(division3); // 1.6666666666666667

 

Example 3: % (Modulus) Operator used to find the remainder from left-hand operand / right-hand operand.

System.out.println(7 % 4); //3
System.out.println(3 % 4); //3
System.out.println(6 % 2); //0
System.out.println(10 % 3); //1

 

Example 4: Increment (++) and Decrement (--) Operators are used to increase/decrease the value of operand by 1.

Hint: There are two forms of increment/decrement operators as prefix form and postfix form. These forms differs as the incement/decrement operation will be affecred instantly or one line later.

int a=5;
System.out.println(a); //5
System.out.println(a++); //5
System.out.println(a); //6

 

int a=5;
System.out.println(a); //5
System.out.println(++a); //6
System.out.println(a); //6

 

int a=5;
System.out.println(a); //5
System.out.println(a++); //5
System.out.println(++a); //7

 

Example 5: Complex problem with the increments/decrements.

int a = 5;
System.out.println(a); //5

int b = a--;
System.out.println(b); //5

int c = a;
System.out.println(c); //4

int d= --c;
System.out.println(d); //3

System.out.println("---");

System.out.println(a); //4
System.out.println(b); //5
System.out.println(c); //3
System.out.println(d); //3