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 an int 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 the toString() 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 are IntVal objects.
  • We get the elements of the list, that are Intval objects and use increment() method of IntVal 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
priya
5 years ago

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.

Best NIOS Coaching in Lucknow

Thanks for the detailed information about wrapper class. that’s very helpful for me.

Back to top button