Practical Usage Scenarios
Common Use Cases for Wrapper Classes
Wrapper classes are essential in various Java programming scenarios, providing powerful type conversion and manipulation capabilities.
1. Collections and Generics
public class CollectionsDemo {
public static void main(String[] args) {
// Generic collections require object types
List<Integer> numberList = new ArrayList<>();
numberList.add(10);
numberList.add(20);
// Sorting collections
Collections.sort(numberList);
}
}
2. Type Conversion and Parsing
public class ConversionDemo {
public static void main(String[] args) {
// String to numeric conversion
int parsedInt = Integer.parseInt("123");
double parsedDouble = Double.parseDouble("3.14");
// Numeric to String conversion
String intToString = Integer.toString(456);
}
}
3. Null Handling and Default Values
public class NullHandlingDemo {
public static void processValue(Integer value) {
// Safe null handling
int safeValue = (value != null) ? value : 0;
System.out.println("Processed Value: " + safeValue);
}
public static void main(String[] args) {
processValue(null); // Handles null gracefully
}
}
Usage Scenarios Flowchart
graph TD
A[Wrapper Class Usage] --> B[Collections]
A --> C[Type Conversion]
A --> D[Null Handling]
A --> E[Method Parameters]
A --> F[Utility Operations]
4. Method Parameters and Return Types
public class MethodParameterDemo {
// Method accepting wrapper type
public static void processNumber(Integer number) {
if (number != null) {
System.out.println("Squared: " + (number * number));
}
}
// Method returning wrapper type
public static Double calculateAverage(List<Integer> numbers) {
return numbers.stream()
.mapToInt(Integer::intValue)
.average()
.orElse(0.0);
}
}
Comparison of Primitive vs Wrapper
Scenario |
Primitive |
Wrapper |
Nullability |
Cannot be null |
Can be null |
Method Calls |
Limited |
Rich utility methods |
Generics |
Not supported |
Fully supported |
Memory Overhead |
Low |
Slightly higher |
5. Mathematical Operations
public class MathOperationsDemo {
public static void main(String[] args) {
// Utility methods
int maxValue = Integer.max(10, 20);
int minValue = Integer.min(5, 15);
// Bitwise operations
String binaryRepresentation = Integer.toBinaryString(42);
System.out.println("Binary: " + binaryRepresentation);
}
}
Advanced Scenario: Stream Processing
public class StreamProcessingDemo {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Stream operations with wrapper classes
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
Optional<Integer> max = numbers.stream().max(Integer::compare);
}
}
Key Takeaways
- Wrapper classes provide extensive functionality
- Essential for collections, generics, and advanced operations
- LabEx recommends mastering these practical scenarios
- Choose between primitive and wrapper types wisely