Type Casting is a method or process that converts a data type into another data type. The conversion is either done by the compiler (automatically) or by developer (explicitly/manually).
Significance
- Data Conversion: It is helpful to perform operations involving variables of different data types. eg, converting
int
todouble
during division for floating point precision. - Compatibility: Some APIs or methods expect parameters of specific data types. Using type cast we can convert our variables to the required ones.
Types of Cast Typing
- Widening Type Casting
- Narrowing Type Casting
Widening (Implicit) Type Casting
This type of casting is done automatically by the Java Compiler. In this type casting, we assign a value of the smaller data type to a variable of larger data type. In this smaller data type is converted into larger type. It is widening casting because it widens the range of values that can be represented.
Conversion does not lose information about the magnitude of the numeric value.
Allowed Widening Type Cast
byte
toshort, int, long, float or double
short
toint, long, float or double
char
toint, long, float or double
int
tolong, float or double
long
tofloat or double
float
todouble
byte b = 127;
short s = 198;
char c = '$';
int i = 1999;
long l = 9899;
float f = 567.23f;
double d = 879797.585;
int i1 = b;
short s1 = b;
int i2 = c;
double d2 = c;
double d3 = f;
Narrowing (Explicit) Type Casting
It is done manually by the Java programmer/developer. It occurs when a value of larger data type is assigned to a variable of smaller data type. It can result in loss of data if the value being cast exceeds the range of the target data type.
Narrowing Type Cast
short
tobyte or char
char
tobyte or short
int
tobyte, short or char
long
tobyte, short, char or int
float
tobyte, short, char, int or long
double
tobyte, short, char, int, long or float
byte b = 127;
short s = 198;
char c = '$';
int i = 1999;
long l = 9899;
float f = 567.23f;
double d = 879797.585;
byte b1 = (byte) s;
char c1 = (char) s;
char c2 = (char) i;
char c3 = (char) l;
int i3 = (int) b;
long l1 = (long) f;
Default Values
In Java, when you declare a variable but don’t initialize it, the variable is assigned a default value based on its data type by the Java Compiler.
Values for
- Primitive Data Types
- byte, short, int, long:
0
- float double:
0.0
- char:
'\u0000' (null character)
- boolean:
false
- byte, short, int, long:
- Reference Data Types: Default values for all reference types (objects) is
null
. - Arrays: Default value of uninitialized array is
null
. - Local Variables: They must be initialized before use else compiler will throw error.