Practical Conversion Examples
Comprehensive Conversion Scenarios
graph LR
A[String] --> B[Primitive]
B --> C[Object]
C --> D[Collection]
String to Primitive Conversions
Integer Conversion
public class IntegerConversion {
public static void main(String[] args) {
String numberStr = "1024";
int intValue = Integer.valueOf(numberStr);
System.out.println("Converted Integer: " + intValue);
}
}
Double Conversion
public class DoubleConversion {
public static void main(String[] args) {
String decimalStr = "3.14159";
double doubleValue = Double.valueOf(decimalStr);
System.out.println("Converted Double: " + doubleValue);
}
}
Boolean Conversion Techniques
Input String |
Conversion Result |
"true" |
true |
"false" |
false |
"TRUE" |
true |
"False" |
false |
public class BooleanConversion {
public static void main(String[] args) {
String trueStr = "true";
String falseStr = "FALSE";
boolean boolTrue = Boolean.valueOf(trueStr);
boolean boolFalse = Boolean.valueOf(falseStr);
System.out.println("Boolean True: " + boolTrue);
System.out.println("Boolean False: " + boolFalse);
}
}
Advanced Conversion Patterns
Handling Numeric Conversions
public class NumericConversions {
public static void main(String[] args) {
// Different numeric conversions
String longStr = "9876543210";
String floatStr = "3.14f";
long longValue = Long.valueOf(longStr);
float floatValue = Float.valueOf(floatStr);
System.out.println("Long Value: " + longValue);
System.out.println("Float Value: " + floatValue);
}
}
Error Handling Strategies
- Use try-catch blocks
- Validate input before conversion
- Provide default values
public class SafeConversion {
public static void main(String[] args) {
try {
int safeValue = Integer.valueOf("not a number");
} catch (NumberFormatException e) {
System.out.println("Invalid conversion: " + e.getMessage());
}
}
}
LabEx Conversion Insights
At LabEx, we recommend practicing these conversion techniques to enhance your Java programming skills and develop robust type transformation capabilities.
- Prefer
valueOf()
over parseXXX()
methods
- Cache frequently used conversions
- Use appropriate data types