2.7 Data Type Conversion in Java

We can assign one primitive data type to another provided there is no possible loss of precision. In such cases, Java automatically performs the data type conversion. For example,
in the code fragment

short s = 6;
int i = s;


we can assign s to i because the precision of a short is less than an int, so there is no possible loss of precision. However, the statement

s = i;

is illegal because there is possible loss of precision. The program will fail to compile. In this case, we need to explicitly cast the data type. This is done by enclosing the target data type with parentheses and prefixing this to the source variable. For example,

s = (short) i;

The loss of precision argument means that we can assign an int to a float, but we need to explicitly cast a float to an int, as follows:

float fvar = 6.2f;
int i = (int) fvar;


Note this truncates the fractional part. Even with a cast we cannot assign a boolean to an integer or real.

No comments:

Post a Comment