Wednesday, May 30, 2018

Casting Incompatible Types using JAVA

Although the automatic type conversions are helpful, they will not fulfill all needs. For
example, what if you want to assign an int value to a byte variable? This conversion
will not be performed automatically, because a byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion, since you are explicitly making
the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast
is simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For
example, the following fragment casts an int to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer
division by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to
an integer type: truncation. As you know, integers do not have fractional components.
Thus, when a floating-point value is assigned to an integer type, the fractional component
is lost. For example, if the value 1.23 is assigned to an integer, the resulting value will
simply be 1. The 0.23 will have been truncated. Of course, if the size of the whole number
component is too large to fit into the target integer type, then that value will be reduced
modulo the target type’s range.
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Let’s look at each conversion. When the value 257 is cast into a byte variable, the
result is the remainder of the division of 257 by 256 (the range of a byte), which is 1 in
this case. When the d is converted to an int, its fractional component is lost. When d is
converted to a byte, its fractional component is lost, and the value is reduced modulo
256, which in this case is 67.
banner
Previous Post
Next Post

0 comments: