Wrapper Classes in Java _ GeeksforGeeks
Wrapper Classes in Java _ GeeksforGeeks
54
Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multith
Output
They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because
primitive types are passed by value).
The classes in java.util package handle only objects and hence
wrapper classes help in this case.
Data structures in the Collection framework, such as ArrayList and
Vector, store only objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.
char Character
byte Byte
short Short
int Integer
Primitive Data Type Wrapper Class
long Long
float Float
double Double
boolean Boolean
1. Autoboxing
class Geeks
{
public static void main(String[] args)
{
char ch = 'a';
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
Output
25
2. Unboxing
class Geeks
{
public static void main(String[] args)
{
Character ch = 'a';
ArrayList<Integer> arrayList
= new ArrayList<Integer>();
arrayList.add(24);
Output
24
Java Wrapper Classes Example
class Geeks {
public static void main(String[] args)
{
// byte data type
byte a = 1;
Output:
Example:
// wrapper class
class Maximum {
private int maxi = 0;
private int size = 0;
public void insert(int x)
{
this.size++;
if (x <= this.maxi)
return;
this.maxi = x;
}
class Geeks {
public static void main(String[] args)
{
Maximum x = new Maximum();
x.insert(12);
x.insert(3);
x.insert(23);
Output
Maximum element: 23
Number of elements inserted: 3