In Java, type casting is a method or process for manually and automatically converting one data type into another. The compiler performs the automatic conversion, while the programmer performs the manual conversion. In this section, we’ll go over typecasting and the various types with examples.
Types of Type Casting
There are two types of typecasting:
- Implicit conversion
- Explicit conversion
Implicit conversion
Implicit type casting is the process of converting a lower data type to a higher one. It’s also known as casting down or implicit conversion. It’s done for you automatically. Furthermore, it is secure because there is no risk of data loss. It occurs when the following occurs:
- Both data types must be compatible with each other.
- The target type must be larger than the source type.
Example:
public class TypeCastingExample
{
public static void main(String args[])
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}
Output:
Before conversion, int value 7
After conversion, long value 7
After conversion, float value 7.0
Explicit conversion
Explicit type casting is the process of converting a higher data type to a lower one. It’s also known as casting up or explicit conversion. The programmer performs this task manually. The compiler will report a compile-time error if we do not perform casting.
Example:
public class TypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output:
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Note: also read about the Operator Precedence & Associativity
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment