#13 Java Type Casting and Conversions

Type Casting and Conversions


Casting is the term used when a value is converted from one data type to another, except for Boolean data types which cannot be converted to any other type. Usually conversion occurs to a data type which has a larger range or else there could be loss of precision.

class Example18


{ //long to double automatic conversion
 public static void main(String args[])
 {
 long L; double D;
 L = 100123285L;
 D = L; // L = D is impossible
System.out.println("L and D: " + L + " " + D);
 }
 }


Predicted Output:


 L and D: 100123285 1.00123285E8

The general formula used in casting is as follows: (target type) expression, where target type could be int, float, or short, e.g. (int) (x/y)

class Example19


{ //CastDemo
public static void main(String args[])
{
double x, y;
byte b;
int i;
char ch;
 x = 10.0; y = 3.0;
 i = (int) (x / y); // cast double to int
System.out.println("Integer outcome of x / y: " + i);
i = 100; b = (byte) i;
System.out.println("Value of b: " + b);
i = 257;b = (byte) i;
System.out.println("Value of b: " + b);
b = 88; // ASCII code for X
ch = (char) b;
System.out.println("ch: " + ch);
}
}

Predicted Output:


Integer outcome of x / y: 3
Value of b: 100
Value of b:
1 ch: X

Comments

Popular Posts