Typecatsing Datatypes
Typecatsing Datatypes
Bharti Sharma
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.
byte -> short -> char -> int -> long -> float -> double
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:
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.
Now that you know how to perform Explicit type casting, let’s move
further and understand how explicit casting can be performed on
Java expressions.
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';
Data Types and Type Conversion Dr. Bharti Sharma
// Declaringinteger variable
ch = num;
// Main class
Data Types and Type Conversion Dr. Bharti Sharma
// 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;
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
}
Data Types and Type Conversion Dr. Bharti Sharma
Output
Conversion of int to byte.
i = 257 b = 1
Conversion of double to byte.
d = 323.142 b= 67
// Main class
class GFG {
{
Data Types and Type Conversion Dr. Bharti Sharma
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);
System.out.println(b);
}
Data Types and Type Conversion Dr. Bharti Sharma
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.