Introduction to Java Wrapper Classes
In Java, primitive data types like int
, char
, boolean
, etc., are not objects. However, sometimes we need to treat them as objects. Java provides a solution to this through Wrapper Classes. Wrapper Classes are classes that encapsulate primitive types within an Object. This tutorial will guide you through the basics of Wrapper Classes in Java, their importance, and how to use them effectively.
Key Concepts Covered:
- What are Wrapper Classes?
- Why use Wrapper Classes?
- How to use Wrapper Classes in Java
- Practical examples to understand Wrapper Classes better
Why Use Wrapper Classes?
Wrapper Classes offer several advantages:
- Conversion: They provide methods to convert primitive data types into objects and vice versa.
- Compatibility: Many utility methods (e.g., sorting, searching) require objects as arguments. Wrapper Classes enable us to use primitive types in such scenarios.
- Nullability: Unlike primitive types, objects can be
null
, making them useful in scenarios where null values are needed.
How to Use Wrapper Classes in Java
Java provides a set of predefined classes under the java.lang
package, which serve as Wrapper Classes for primitive types. Here are the commonly used ones:
Integer
: Wrapsint
Double
: Wrapsdouble
Boolean
: Wrapsboolean
Character
: Wrapschar
Byte
: Wrapsbyte
Short
: Wrapsshort
Long
: Wrapslong
Float
: Wrapsfloat
Example 1: Converting Primitive Type to Wrapper Object
// Converting int to Integer
int num = 10;
Integer obj = Integer.valueOf(num);
Example 2: Converting Wrapper Object to Primitive Type
// Converting Integer to int
Integer obj = 10;
int num = obj.intValue();
Example 3: Auto-Boxing and Auto-Unboxing
// Auto-Boxing
Integer obj = 10;
// Auto-Unboxing
int num = obj;
Practical Examples
Let’s explore a practical example where Wrapper Classes are beneficial:
import java.util.ArrayList;
public class WrapperExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10); // Auto-Boxing
numbers.add(20);
int sum = 0;
for(Integer num : numbers) {
sum += num; // Auto-Unboxing
}
System.out.println("Sum: " + sum);
}
}
In this example, we store integers in an ArrayList
using Integer
objects. We can perform arithmetic operations directly on these objects due to Auto-Unboxing.
Conclusion
Wrapper Classes in Java provide a bridge between primitive types and objects, offering flexibility and compatibility in various scenarios. By understanding their usage and leveraging them effectively, you can write cleaner and more efficient Java code. Practice the examples provided to solidify your understanding.