Diving by zero in java

Java has some unusual and often unexpected results when dividing by zero when using variables of type int or double.

If you try and divide where both variables are of the type int, a “/ by zero” exception will be thrown.

If, however, you make one of the operands a double, no exception is thrown, and the operation completes successfully. It is important that at least one of the operands and not just the answer is of type double for the statement to complete so the operation itself is done with doubles. If you print the answer, the text “infinity” or “-infinity” will be output.

Why does this happen?

In short, ints have no value for infinity or values that aren’t a number. This means that when 2 ints are divided by zero, the result will always be an exception as the data type has no way to represent the result. Doubles on the other hand are floating point numbers, and floating point numbers can represent infinity or results that aren’t numbers so an operation like dividing by zero is completely valid.

In the examples below, you can see that by making just one of the operands a double, no runtime exception is thrown when dividing by zero and the value of the result is “infinity”. The same operations with ints simply throw an exception.


//Example of standard division of positive ints. 
//output= 4
<%
int aa = 12;
int bb = 3; 
int answer;
try {
answer = aa/bb;
out.println(answer);
} catch (Exception e) {
	out.println("I am a runtime exception!");
}

//Example of dividing by zero using ints.
//output = exception. Exception message: / by zero
int a2 = 12;
int b2 = 0; 
int answer2;
try {
answer2 = a2/b2;
out.println(answer2);
} catch (Exception e) {
	out.println("I am a runtime exception. Exception message: " + e.getMessage());
}

//Example of an int divided by a double. As one of the operands is a double, the answer to will be a double. This works and the answer comes out to be NaN (Not a Number). See the output of 'Infinity' from the below code. 
//output = Infinity 
int a3 = 12;
double b3 = 0; //one of the divisors needs to be a double to work. 
double answer3;
try {
answer3 = a3/b3;
out.println(answer3);
} catch (Exception e) {
	out.println("I am a runtime exception. Exeption message: " + e.getMessage());
}

//Example of int divided by an int.
//output = I am a runtime exception. Exception message: / by zero
int a4 = 12;
int b4 = 0; //one of the divisors needs to be a double to work. 
double answer4;
try {
answer4 = a4/b4;
out.println(answer4);
} catch (Exception e) {
	out.println("I am a runtime exception. Exception message: " + e.getMessage());
}

Leave a Reply

Your email address will not be published. Required fields are marked *