Practical Conversion Examples
Real-World Conversion Scenarios
import java.util.Scanner;
public class UserInputConversion {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Converting user input to different types
System.out.print("Enter your age: ");
String ageInput = scanner.nextLine();
int age = Integer.parseInt(ageInput);
System.out.print("Enter your height (meters): ");
String heightInput = scanner.nextLine();
double height = Double.parseDouble(heightInput);
// Implicit string conversion
String userProfile = "User Profile: " + age + " years, " + height + "m";
System.out.println(userProfile);
}
}
graph TD
A[Raw Data] --> B[Conversion Process]
B --> C[Formatted String]
C --> D[Logging/Display]
public class LoggingConversion {
public static void main(String[] args) {
// Complex object conversion
Product product = new Product("LabEx Notebook", 599.99, 10);
// Implicit conversion in logging
System.out.println("Product Details: " + product);
}
static class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
@Override
public String toString() {
return String.format("Name: %s, Price: $%.2f, Quantity: %d",
name, price, quantity);
}
}
}
Conversion Method Comparison
Conversion Method |
Use Case |
Performance |
Example |
Concatenation |
Simple conversions |
Moderate |
"Value: " + 42 |
String.valueOf() |
Safe conversion |
Good |
String.valueOf(3.14) |
toString() |
Object-specific |
Customizable |
object.toString() |
3. Error Handling in Conversions
public class SafeConversionDemo {
public static void main(String[] args) {
// Safe conversion with error handling
String[] numbers = {"100", "200", "abc", "300"};
for (String num : numbers) {
try {
int value = Integer.parseInt(num);
System.out.println("Converted: " + value);
} catch (NumberFormatException e) {
System.out.println("Conversion error: " + num);
}
}
}
}
Advanced Conversion Techniques
Conditional Conversion
public class ConditionalConversionDemo {
public static void main(String[] args) {
Object[] mixedData = {42, "Hello", 3.14, true};
for (Object data : mixedData) {
// Conditional string conversion
String result = (data != null)
? "Converted: " + data
: "Null value";
System.out.println(result);
}
}
}
Key Takeaways
- Choose appropriate conversion method based on context
- Handle potential conversion errors
- Be mindful of performance implications
- Leverage Java's built-in conversion mechanisms
By mastering these practical conversion examples, developers can write more robust and flexible Java applications, especially when working on platforms like LabEx.