JAVA

What is wrapper class?

Java uses primitive data types (also called simple types), such as int or double, to hold the basic data types supported by language. But many times when you will need an object representation of primitive types, Wrapper Class is used.

Wrapper Class

  • In Java, There is a Wrapper Class for every Primitive data type.
  • Basically the Wrapper Classes encapsulate a Primitive data type within an Object. For example, the wrapper class for int is Integer, the class for float is Float, and the class for char is Character and so on.
  • The type wrappers are Double, Float, Long, Integer, Short, Byte, Character and Boolean.
  • These classes offer a wide array of methods that allows you to fully integrate the primitive data type into Java’s object hierarchy.
  • These classes are known as Wrapper Classes, because they "wrap" the primitive data type into an object of that class.
  • The Wrapper Classes are part of the java.lang package which is imported by default into all java programs.

Purpose of Wrapper Classes in JAVA

The Wrapper Classes in Java servers two primary purpose.

  1. To provide mechanism to "wrap" primitive values in an object so that primitives can do activities reserved for the objects like, being added to ArrayList, Hashset, HashMap etc. collection.
  2. Wrapper Classes provide many utility functions for primitives, Most of these functions are related to various conversions;
    • Converting primitives to and from String object, and converting primitives and String Objects to and from different bases (or radix), such as binary, octal and hexadecimal.

The following statements illustrate the difference between a primitive data type and an object of a Wrapper Class.

Syntax:

int x = 25;//declaration of int variable named x and initializes value with 25.
Integer y = new Integer(25);// initializes an Integer object.
// the object Initializes with the value 33 and a reference to the
// object is assigned to the object variable y

Example:

class WrapDemo
{
    public static void main (String args[]))
    {
        Integer iOb = new Integer(5);
        int i = iOB.intValue();
        System.out.println("Integer Wrapper Class Object: " + iOb);
        System.out.println("Integer Primitive type: " + i);
    }
}

Output:

Command Prompt
Integer Wrapper Class Object: 5
Integer Primitive type: 5



Subscribe us on Youtube

Share This Page on

Question


Bhavesh Bandhiya | 22-Nov-2016 10:20:13 pm

required full stock example of program and online java compiler


Ask Question