Signup/Sign In
PUBLISHED ON: JANUARY 28, 2021

Integer Division in Java

In this tutorial, we will learn about integer division in Java. Let's say we have two variables of integer type a=25 and b=5 and we want to perform division.

When it comes to a decision of maintaining precision or avoiding precision mainly at the time of division because while doing division there are high chances of losing precision.

Example of simple division

In the given example we have three int type variables a, b, c and we are storing division of a & b into c. We recommend you to run this example and observe the output and match your observations with whatever we discussed below.

public class StudyTonight 
{ 
	public static void main(String[] args)   
	{ 
		 int a = 25;
		 int b = 5;
		 int c = a / b;
		 System.out.println(a+"/"+b+"="+c);
	} 
}


25/5=5

In the above case, the division will work finely because all the variables are in the form of an integer and 5 divide 25 completely. Think about 10/3 definitely c cannot store 3.3333... as it is an int type of a variable and able to store integer data only and it will hold just 3. In the below case it is not considering a reminder.

Example: losing data

Here, we are dividing two integers and storing the result into int that leads to loss of data because integer does not hold decimal place values.

public class StudyTonight 
{ 
	public static void main(String[] args)   
	{ 
		 int a = 10;
		 int b = 3;
		 int c = a / b;
		 System.out.println(a+"/"+b+"="+c);
	} 
}


10/3=3

Now let's bring the idea of doing real division where we will store the value in double.

Example

In the code given below, to observe the output of what happens when we change the datatype of variables from float to int and vice versa. You will get integers or real numbers.

public class StudyTonight 
{ 
	public static void main(String[] args)   
	{ 
		int ans1 = 10 / 3;
		double ans2 = 10.0 / 3;
		double ans3 = 10 / 3.0;
		double ans4 = 10.0 / 3.0;
		double ans5 = 10 / 3;		 		 
		System.out.println("10 / 3 = "+ans1);
		System.out.println("10.0 / 3 = "+ans2);
		System.out.println("10 / 3.0 = "+ans3);
		System.out.println("10.0 / 3.0 = "+ans4);
		System.out.println("10 / 3 = "+ans5);	
	}
}


10 / 3 = 3
10.0 / 3 = 3.3333333333333335
10 / 3.0 = 3.3333333333333335
10.0 / 3.0 = 3.3333333333333335
10 / 3 = 3.0

Conclusion:

After implementing all the above codes we can conclude some important observation based on the datatype of divisor and dividend

int / int = int

double / int = double

int / double = double

double / double = double



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.