Type Conversion Rules
Implicit Type Conversion (Widening)
Implicit type conversion occurs automatically when converting a smaller type to a larger type. This process is also known as widening or upcasting.
Conversion Hierarchy
graph TD
A[byte] --> B[short]
B --> C[int]
C --> D[long]
D --> E[float]
E --> F[double]
Widening Conversion Example
public class WideningConversionDemo {
public static void main(String[] args) {
byte smallNumber = 100;
int convertedNumber = smallNumber; // Implicit conversion
long largeNumber = convertedNumber; // Another implicit conversion
System.out.println("Byte to Int: " + convertedNumber);
System.out.println("Int to Long: " + largeNumber);
}
}
Explicit Type Conversion (Narrowing)
Explicit type conversion requires manual casting and may result in data loss.
Conversion Rules
Source Type |
Target Type |
Casting Required |
Potential Data Loss |
long |
int |
Yes |
Possible |
int |
short |
Yes |
Possible |
int |
byte |
Yes |
Possible |
Narrowing Conversion Example
public class NarrowingConversionDemo {
public static void main(String[] args) {
long largeNumber = 1000000L;
int convertedNumber = (int) largeNumber; // Explicit casting
short smallNumber = (short) convertedNumber; // Further narrowing
System.out.println("Long to Int: " + convertedNumber);
System.out.println("Int to Short: " + smallNumber);
}
}
Best Practices for Type Conversion
- Always use explicit casting when narrowing types
- Be cautious of potential data loss
- Check value ranges before conversion
- Use LabEx platform for safe practice and testing
Overflow and Underflow Considerations
When converting between types, be aware of potential overflow or underflow:
public class OverflowDemo {
public static void main(String[] args) {
int maxInt = Integer.MAX_VALUE;
byte smallByte = (byte) maxInt; // Unexpected result
System.out.println("Overflow Result: " + smallByte);
}
}
Advanced Conversion Techniques
- Use
Integer.valueOf()
for object conversions
- Utilize
Number
class methods for type transformations
- Implement custom conversion logic when needed