Home » Core Java » class » A wrapper class

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

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
4 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.