Type casting in Java refers to converting a value of one data type to another. This is often necessary when you're working with different types of variables or objects in your program. Java supports two types of casting:
- Implicit Casting (Widening Conversion): This is when you convert a smaller data type into a larger one, as it can be done automatically by the Java compiler without loss of information. For example:
int numInt = 100;
double numDouble = numInt; // Implicit casting from int to double
System.out.println(numDouble); // Output: 100.0
System.out.println(numDouble); // Output: 100.0
- Explicit Casting (Narrowing Conversion): This is when you convert a larger data type into a smaller one, which may result in loss of data. It requires explicit declaration and is done by placing the type in parentheses before the value. For example:
Here are a few more examples demonstrating different types of casting:
// Widening Conversion (Implicit Casting)
int intValue = 100;
long longValue = intValue; // Implicit casting from int to long
float floatValue = longValue; // Implicit casting from long to float
double doubleValue = floatValue; // Implicit casting from float to double
// Narrowing Conversion (Explicit Casting)
double doubleNum = 100.55;
int intNum = (int) doubleNum; // Explicit casting from double to int
short shortNum = (short) intNum; // Explicit casting from int to short
byte byteNum = (byte) shortNum; // Explicit casting from short to byte
Remember, when narrowing conversions are performed, there is a risk of losing data or precision, so be cautious when using explicit casting.
Tags:
Core java