Java Reference
In-Depth Information
float floatB = 6.82f;
//Widening conversion
double doubleX = (double) intA;
//Narrowing conversion
int intY = (int) floatB;
// print out the values
System.out.println("The value of intA is: " + intA +".");
System.out.println("The value of floatB is: " + floatB +".");
System.out.println("The value of doubleX is: " + doubleX +".");
System.out.println("The value of intY is: " + intY +".");
}
}
The output of this program is:
The value of intA is: 4.
The value of floatB is: 6.82.
The value of doubleX is: 4.0.
The value of intY is: 6.
Observe how narrowing the conversion of the floating point number
6.82
caused the floating point
to be dismissed. Consider the following example:
public class AnotherTypeCastingExample {
public static void main(String[] args){
float x = 3/9;
float y = (float) 3/(float) 9;
float z = (float) 3/9;
System.out.println("The value of x is: " + x +".");
System.out.println("The value of y is: " + y +".");
System.out.println("The value of z is: " + z +".");
}
}
The output of this program is:
The value of x is: 0.0.
The value of y is: 0.33333334.
The value of z is: 0.33333334.
Let's now discuss why Java gives this output. For the first expression,
float
x
= 3/9;
, Java con-
siders both operands as integers and thus uses integer division. The result of this is zero, and Java
will then do the widening conversion to
float
, yielding a zero floating number. For the second
expression,
float
y
= (float) 3/(float) 9;
, Java will first perform the widening conversion
for the values
3
and
9
, and then do the floating point division and assign the result to the floating
point variable
y
. For the third expression,
float
z
= (float) 3/9;
, Java will first do a widening
conversion to the value
3
, and then do an (implicit) widening conversion to the value
9
. It will then
perform the floating point division and assign the desired value to the floating point variable
z
.
Search WWH ::
Custom Search