Academic Java    Java Tutorial  >  Basics  >  casting type conversion

casting type conversion Example

Java provides a cast construct (using parentheses around the type converted to) to force any of the following type conversions:

byte to char
short to byte, char
char to byte, short
int to byte, short, char
long to byte, short, char, int
float to byte, short, char, int, long
double to byte, short, char, int, long, float
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class CastTypeConversionExample {

   public static void main(String[] args) {

      double d = 1230.56789;

      int i = (int)d;

      float f = (float)d;

      long l = (long)f;

      char c = (char)i;

      short sh = (short)c;

      byte b = (byte)sh;

   }

}

5 A double is initialized.

7 A double is cast to an int and is then assigned to an int.  It is truncated (the decimal fraction is removed i.e. rounding to the nearest integer does not occur). The value assigned to the int is 1230.

9 A double is cast to a float and then assigned to a float.  Note that some precision in the fractional part of the value is lost. The value assigned is 1230.5679F.

11 A float is cast to a long and is then assigned to a long.  Note that the value is truncated. The value asigned is 1230L.

13 An int is cast to a char and is then assigned to a char.  The resulting value of such a conversion is not necessarily a character that can be printed.

15 A char is cast to a short and is then assigned to a short.  The value assigned is 1230.

17 A short is cast to a byte and is then assigned to a byte.  Note what happens to the value. 8 bits of the 16-bit short value are stripped to provide an 8-bit byte with the value -50.