Type Conversion Rules
Implicit Type Conversion (Widening)
Implicit type conversion occurs automatically when converting a smaller type to a larger type. This process is safe and does not result in data loss.
graph TD
A[Implicit Conversion] --> B[byte]
B --> C[short]
C --> D[int]
D --> E[long]
E --> F[float]
F --> G[double]
Conversion Hierarchy
Source Type |
Target Type |
Conversion Type |
byte |
short |
Implicit |
short |
int |
Implicit |
int |
long |
Implicit |
long |
float |
Implicit |
float |
double |
Implicit |
Explicit Type Conversion (Narrowing)
Explicit conversion requires manual casting and may result in data loss or unexpected results.
Casting Rules
public class TypeConversionDemo {
public static void main(String[] args) {
// Implicit conversion
int intValue = 100;
long longValue = intValue; // Automatic widening
// Explicit conversion
long largeNumber = 1_000_000L;
int smallNumber = (int) largeNumber; // Explicit narrowing
// Potential data loss
double doubleValue = 123.45;
int truncatedValue = (int) doubleValue; // Loses decimal part
System.out.println("Truncated Value: " + truncatedValue);
}
}
Conversion Precautions
- Always check the range of target type
- Use explicit casting carefully
- Be aware of potential data loss
- Handle overflow scenarios
Advanced Conversion Techniques
Number Class Conversion
public class NumberConversionDemo {
public static void main(String[] args) {
// Using Number class methods
String numberString = "123";
int parsedInt = Integer.parseInt(numberString);
long parsedLong = Long.parseLong(numberString);
double parsedDouble = Double.parseDouble(numberString);
System.out.println("Parsed Integers: " + parsedInt);
}
}
LabEx Recommendation
When working with type conversions, LabEx suggests:
- Understanding type ranges
- Using appropriate conversion methods
- Implementing error handling
- Practicing safe type casting
Conversion Complexity
graph LR
A[Simple Conversion] --> B[Implicit Conversion]
A --> C[Explicit Conversion]
C --> D[Potential Data Loss]
C --> E[Careful Casting Required]