Java Wrapper Class
Java wrapper class is a class that provides a way to use primitive data types as objects. In Java, primitive data types are not objects, and they cannot be used in collections (such as ArrayLists, HashSets, and HashMaps). Wrapper classes provide a way to use primitive data types in collections. There are eight wrapper classes in Java:
- Byte
- Short
- Integer
- Long
- Float
- Double
- Character
- Boolean
Syntax
Here's an example of how to declare a wrapper class in Java:
Integer myInteger = new Integer(42);
Boolean myBoolean = new Boolean(true);
You can also use the valueOf method to create a wrapper class:
Integer myInteger = Integer.valueOf(42);
Boolean myBoolean = Boolean.valueOf(true);
Example
Here's an example that demonstrates the use of wrapper classes in Java:
import java.util.ArrayList;
public class WrapperClassExample {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(1);
numbers.add(new Integer(2));
numbers.add(Integer.valueOf(3));
int a = numbers.get(0);
Integer b = numbers.get(1);
Integer c = numbers.get(2);
int d = c.intValue();
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output:
a = 1
b = 2
c = 3
d = 3
Explanation
In this example, we create an ArrayList of Integer objects and add three values to it. We then retrieve the values from the ArrayList using different techniques.
- We retrieve the first value as an int using auto-unboxing.
- We retrieve the second value as an Integer object.
- We retrieve the third value as an Integer object using the valueOf method.
- We retrieve the int value of the third value using the intValue method.
We then print the values to the console.
Use
Wrapper classes are commonly used when working with collections or when passing parameters to methods that require objects. They are also useful when working with other Java libraries that require objects instead of primitive data types.
Important Points
- Wrapper classes provide a way to use primitive data types as objects in Java.
- There are eight wrapper classes in Java: Byte, Short, Integer, Long, Float, Double, Character, and Boolean.
- Wrapper classes are commonly used when working with collections or when passing parameters to methods that require objects.
Summary
Wrapper classes are an essential part of the Java programming language. They provide a way to use primitive data types as objects and are commonly used when working with collections or when passing parameters to methods that require objects. Understanding how to use wrapper classes will help you become a better Java programmer.