Type Conversion is the process of converting one data type into another.
- In Java, this is especially important when performing operations between different types (like int and float).
Two Types of Type Conversion in Java:
- Implicit Conversion
- Explicit Conversion
1.) Implicit Conversion:
Automatically done by the Java compiler when converting a smaller type to a larger type.
Syntax:
dataType2 var = var1; // var1 is of smaller typeExample:
int a = 10;
double b = a; // int to double
System.out.println(b); // Output: 10.02.) Explicit Conversion:
Must be manually done by the programmer when converting a larger type to a smaller type.
Syntax:
dataType2 var = (dataType2) var1; // var1 is of larger typeExample:
double a = 10.5;
int b = (int) a; // double to int
System.out.println(b); // Output: 10Best Practices:
- Use implicit conversion when possible.
- Use explicit casting carefully to avoid unexpected results.
- Always test for data loss when casting larger to smaller types.
