Java Reference
In-Depth Information
and the result is always an integer. If either or both of the operands of the division operator are float or double type,
floating-point division is performed and the result is not truncated. For example,
float f1;
// 15.0F and 4.0F are of float type. So, the expression 15.0F/4.0F is of the type float.
// The result 3.75F is assigned to f1.
f1 = 15.0F/4.0F;
// 15 is of type int and 4.0F is of type float. The expression 15/4.0F is of type float.
// The result 3.75F is assigned to f1.
f1 = 15/4.0F;
// An error. 15.0 is of the type double and 4.0F is of the type float.
// The expression 15.0/4.0F is of type double. The result 3.75 is of the
// type double and cannot be assigned to f1.
f1 = 15.0/4.0F;
f1 = (float)(15.0/4.0F); // Ok. 3.75F is assigned to f1
// 15 and 4 are of the type int. The expression 15/4 is of type int.
// An integer division is performed. The result 3 is assigned to f1,
// because int to float assignment is allowed
f1 = 15/4;
What happens when you try to divide a number (integer or floating-point) by 0 (zero)? The result of dividing a
number by zero depends on the type of division. If an integer division is performed on the number, dividing by zero
results in a runtime error. If you write expression 3/0 in a Java program, it compiles fine, but it gives error when it is
executed at runtime. For example,
int i = 2;
int j = 5;
int k = 0;
i = j/k; // A runtime error. Divide by zero
i = 0/0; // A runtime error. Divide by zero
If either operand of the division operator is a floating-point number, a floating-point division is performed and
the result of dividing the number by zero is not an error. If the dividend (in 7/2, 7 is the dividend and 2 is the divisor)
is a non-zero number in a floating-point divide-by-zero operation, the result is either positive infinity or a negative
infinity. If the dividend is a floating-point zero (e.g. 0.0 or 0,0F), the result is NaN . For example,
float f1 = 2.5F;
double d1 = 5.6;
f1 = 5.0F/0.0F; // Float.POSITIVE_INFINITY is assigned to f1
f1 = -5.0F/0.0F; // Float.NEGATIVE_INFINITY is assigned to f1
f1 = -5.0F/-0.0F; // Float.POSITIVE_INFINITY is assigned to f1
f1 = 5.0F/-0.0F; // Float.NEGATIVE_INFINITY is assigned to f1
d1 = 5.0/0.0; // Double.POSITIVE_INFINITY is assigned to d1
d1 = -5.0/0.0; // Double.NEGATIVE_INFINITY is assigned to d1
d1 = -5.0/-0.0; // Double.POSITIVE_INFINITY is assigned to d1
d1 = 5.0/-0.0; // Double.NEGATIVE_INFINITY is assigned to d1
Search WWH ::




Custom Search