Conversion Techniques
Implicit Type Conversion (Widening)
Implicit conversion occurs automatically when converting to a larger type:
public class ImplicitConversionDemo {
public static void main(String[] args) {
byte byteValue = 42;
int intValue = byteValue; // Automatic widening
long longValue = intValue; // Another widening conversion
double doubleValue = longValue; // Widening to floating-point
System.out.println("Byte to Int: " + intValue);
System.out.println("Int to Long: " + longValue);
System.out.println("Long to Double: " + doubleValue);
}
}
Explicit Type Conversion (Narrowing)
Explicit conversion requires manual casting:
public class ExplicitConversionDemo {
public static void main(String[] args) {
double doubleValue = 123.45;
long longValue = (long) doubleValue; // Explicit casting
int intValue = (int) longValue; // Narrowing conversion
short shortValue = (short) intValue; // Further narrowing
System.out.println("Double to Long: " + longValue);
System.out.println("Long to Int: " + intValue);
System.out.println("Int to Short: " + shortValue);
}
}
Conversion Methods and Utilities
Parsing Strings to Numbers
public class ParsingDemo {
public static void main(String[] args) {
String numberString = "123";
int parsedInt = Integer.parseInt(numberString);
long parsedLong = Long.parseLong(numberString);
double parsedDouble = Double.parseDouble(numberString);
System.out.println("Parsed Int: " + parsedInt);
System.out.println("Parsed Long: " + parsedLong);
System.out.println("Parsed Double: " + parsedDouble);
}
}
Conversion Flow Chart
graph TD
A[Original Number Type] --> B{Conversion Type}
B --> |Widening| C[Larger Type]
B --> |Narrowing| D[Smaller Type]
B --> |String Parsing| E[Numeric Type from String]
Conversion Techniques Comparison
Conversion Type |
Description |
Example |
Potential Issues |
Implicit |
Automatic, no data loss |
int x = (byte)10 |
None |
Explicit |
Manual casting |
long y = (long)intValue |
Potential data truncation |
Parsing |
Converting from String |
Integer.parseInt() |
Possible NumberFormatException |
Special Conversion Considerations
- Always check for potential data loss during narrowing conversions
- Use wrapper classes for safe conversions
- Handle potential exceptions when parsing strings
Advanced Conversion Techniques
public class AdvancedConversionDemo {
public static void main(String[] args) {
// Using wrapper classes
Integer intWrapper = Integer.valueOf("123");
Double doubleWrapper = Double.valueOf(intWrapper);
// Hexadecimal and binary conversions
int hexValue = Integer.parseInt("FF", 16);
int binaryValue = Integer.parseInt("1010", 2);
System.out.println("Hex to Decimal: " + hexValue);
System.out.println("Binary to Decimal: " + binaryValue);
}
}
Key Takeaways
- Understand the difference between widening and narrowing conversions
- Use appropriate conversion methods
- Be cautious of potential data loss
- Leverage LabEx programming environments for safe number conversions