Typecatsing
Typecatsing
Typecatsing
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
When you assign the value of one data type to another, you should
be aware of the compatibility of the data type.
double -> float -> long -> int -> char -> short -> byte
Widening Casting
This type of casting takes place when two data types are automatically
converted. It is also known as Implicit Conversion.
This happens when the two data types are compatible and also when we
assign the value of a smaller data type to a larger data type.
For Example,
The numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char
and boolean are not compatible with each other.
Output:
1 Int value 200
2 Long value 200
3 Float value 200.0
Narrowing Casting
In this case, if you want to assign a value of larger data type to a smaller
data type, you can perform Explicit type casting or narrowing. This is
useful for incompatible data types where automatic conversion cannot be
done.
Practice questions:
char and number are not compatible with each other. Let’s see when we try
to convert one into another.
Java
// Main class
char ch = 'c';
// Declaringinteger variable
// Main class
// Double datatype
double d = 100.04;
long l = (long)d;
int i = (int)l;
// Print statements
Output
Double value 100.04
Long value 100
Int value 100
Note: While assigning value to byte type the fractional part is lost and is
reduced to modulo 256(range of byte).
Example:
Java
// Main class
class GFG {
byte b;
// Declaring and initializing integer and double
int i = 257;
double d = 323.142;
// Display message
// i % 256
b = (byte)i;
// Print commands
System.out.println(
// d % 256
b = (byte)d;
// Print commands
}
}
Output
Conversion of int to byte.
i = 257 b = 1
// Main class
class GFG {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
// The Expression
Output
result = 626.7784146484375
Example:
Java
// in Integer to Byte
// Main class
class GFG {
byte b = 50;
b = (byte)(b * 2);
// Display value in byte
System.out.println(b);
Output
100
Note: In case of single operands the result gets converted to int and
then it is typecast accordingly, as in the above example.