class
A wrapper class
This is an example of how to create a wrapper class. A wrapper class is defined as a class in which a primitive value is wrapped up. Here, we create a wrapper class for an int
value:
- We have a class
IntVal
, that has anint
field, getter and setter for the field, a constructor using its field and a method,increment()
that increases by one the int field. It also overrides thetoString()
method of Object, and returns the String object that represents the int field. - We create a new ArrayList and populate it with values, using
add(Object o)
. The objects added to the list areIntVal
objects. - We get the elements of the list, that are
Intval
objects and useincrement()
method ofIntVal
to increase the values of the objects.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.ArrayList; import java.util.List; class IntVal { private int i; public IntVal(int a) { i = a; } public int getVal() { return i; } public void setValue(int a) { this.i = a; } public void increment() { i++; } @Override public String toString() { return Integer.toString(i); } } public class WrapperClass { public static void main(String[] args) { List list = new ArrayList(); for (int i = 0; i < 10; i++) { list.add(new IntVal(i)); } System.out.println(list); for (int i = 0; i < list.size(); i++) { ((IntVal) list.get(i)).increment(); } System.out.println(list); } }
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This was an example of how to create a wrapper class in Java.
Wrapper Classes are Classes that have written to make objects from the primitive types in Java. They are used to wrap the primitive values in an object.Many thanks for sharing this.
Thanks for the detailed information about wrapper class. that’s very helpful for me.