Вы находитесь на странице: 1из 10

Description

Each of Java's eight primitive data types has a class dedicated to it. These 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.
The wrapper classes in java servers two primary purposes.

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.

To provide an assortment of utility functions for primitives like converting primitive types to and from

string objects, converting to various bases like binary, octal or hexadecimal, or comparing various objects.

The following two statements illustrate the difference between a primitive data type and an
object of a wrapper class:
int x = 25;

Integer y = new Integer(33);

The first statement declares an int variable named x and initializes it with the value 25. The
second statement instantiates an Integer object. The object is initialized with the value 33 and
a reference to the object is assigned to the object variable y.
Below table lists wrapper classes in Java API with constructor details.

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char

int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String

Below is wrapper class hierarchy as per Java API


As explain in above table all wrapper classes (except Character) take String as argument
constructor. Please note we might get NumberFormatException if we try to assign invalid
argument in constructor. For example to create Integer object we can have following syntax.
Integer intObj = new Integer (25);

Integer intObj2 = new Integer ("25");

Here in we can provide any number as string argument but not the words etc. Below statement
will throw run time exception (NumberFormatException)
Integer intObj3 = new Integer ("Two");

The following discussion focuses on the Integer wrapperclass, but applies in a general sense
to all eight wrapper classes.
The most common methods of the Integer wrapper class are summarized in below table.
Similar methods for the other wrapper classes are found in the Java API documentation.

Method Purpose

parseInt(s) returns a signed decimal integer value equivalent to string s

toString(i) returns a new String object representing the integer i

byteValue() returns the value of this Integer as a byte

doubleValue() returns the value of this Integer as an double

floatValue() returns the value of this Integer as a float

intValue() returns the value of this Integer as an int

shortValue() returns the value of this Integer as a short

longValue() returns the value of this Integer as a long

int compareTo(int Compares the numerical value of the invoking object with that of i.
i) Returns 0 if the values are equal. Returns a negative value if the invoking
object has a lower value. Returns a positive value if the invoking object
has a greater value.

static int Compares the values of num1 and num2. Returns 0 if the values are equal.
compare(int num1, Returns a negative value if num1 is less than num2. Returns a positive
int num2) value if num1 is greater than num2.
boolean Returns true if the invoking Integer object is equivalent to intObj.
equals(Object Otherwise, it returns false.
intObj)

Lets see java program which explain few wrapper classes methods.
view plaincopy to clipboardprint?

1. package WrapperIntro;

2. public class WrapperDemo {

3. public static void main (String args[]){

4. Integer intObj1 = new Integer (25);

5. Integer intObj2 = new Integer ("25");

6. Integer intObj3= new Integer (35);

7. //compareTo demo

8. System.out.println("Comparing using compareTo Obj1 and Obj2: " + intObj1.compareTo(intObj2));

9. System.out.println("Comparing using compareTo Obj1 and Obj3: " + intObj1.compareTo(intObj3));

10. //Equals demo

11. System.out.println("Comparing using equals Obj1 and Obj2: " + intObj1.equals(intObj2));

12. System.out.println("Comparing using equals Obj1 and Obj3: " + intObj1.equals(intObj3));

13. Float f1 = new Float("2.25f");

14. Float f2 = new Float("20.43f");

15. Float f3 = new Float(2.25f);

16. System.out.println("Comparing using compare f1 and f2: " +Float.compare(f1,f2));

17. System.out.println("Comparing using compare f1 and f3: " +Float.compare(f1,f3));

18. //Addition of Integer with Float

19. Float f = intObj1.floatValue() + f1;

20. System.out.println("Addition of intObj1 and f1: "+ intObj1 +"+" +f1+"=" +f );

21. }

22.

23. }

Output
valueOf (), toHexString(), toOctalString() and toBinaryString()
Methods:
This is another approach to create wrapper objects. We can convert from binary or octal or
hexadecimal before assigning value to wrapper object using two argument constructor. Below
program explains the method in details.
view plaincopy to clipboardprint?

1. package WrapperIntro;

2. public class ValueOfDemo {

3. public static void main(String[] args) {

4. Integer intWrapper = Integer.valueOf("12345");

5. //Converting from binary to decimal

6. Integer intWrapper2 = Integer.valueOf("11011", 2);

7. //Converting from hexadecimal to decimal

8. Integer intWrapper3 = Integer.valueOf("D", 16);

9. System.out.println("Value of intWrapper Object: "+ intWrapper);

10. System.out.println("Value of intWrapper2 Object: "+ intWrapper2);

11. System.out.println("Value of intWrapper3 Object: "+ intWrapper3);

12. System.out.println("Hex value of intWrapper: " + Integer.toHexString(intWrapper));

13. System.out.println("Binary Value of intWrapper2: "+ Integer.toBinaryString(intWrapper2));

14. }

15. }

Output
Summary

Each of primitive data types has dedicated class in java library.

Wrapper class provides many methods while using collections like sorting, searching etc.

Why do we need wrapper classes in java?


Do we really need wrapper classes or wrapper data types in java? Cant we use primitive data types directly instead of wrapper classes? Actually we
can use primitive types in many places but not all. In some cases we cant use primitive values as is, so wrapper classes are needed/required. For
example, if we need to store numbers in a collection, we cant use primitives because collections such as List, Set, and Map need objects as their
elements. In such cases you must use wrapper classes.

What is the difference between primitive data types and wrapper classes in java?
The main difference between primitive data types and wrapper classes (wrapper types) in java is that the primitive types can be used as raw data
for operations such as arithmetic, logical, etc. and wrapper classes acts as data holders for these primitive data types.

Important note: The primitive data type values will be stored in Stack Memory whereas wrapper class objects (like any other java objects) are stored
in Heap Memory.

Use of wrapper class in java


Although, the primary purpose/use of wrapper classes in java is to wrap primitive values, there are few other uses/advantages of wrapper
classes. One feature is to use constants defined by the wrapper class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower
bounds of the data type, and the other application is to use wrapper class methods for converting values to and from other primitive data types, for
converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Creating objects of the Wrapper classes

All the wrapper classes have constructors which can be used to create the corresponding Wrapper class objects by passing either a
String or a variable of the same data type as that of the type to which the wrapper class corresponds, except for the Character
wrapper class whose object cannot be created with a String. Also, the Float wrapper class allows its object to be created using a
double value.

For example, we can create an Integer object which wraps the int 34 in either of the following two ways:

Integer intObject = new Integer (34);


Integer intObject = new Integer ( "34");

Retrieving the value wrapped by a wrapper class object

Each of the eight wrapper classes have a method to retrieve the value that was wrapped in the object. These methods have the
form *Value() where star refers to the corresponding data type. For example, to retrieve the value stored in the Integer object
intObject, we use the following statement.

int x = intObject.intValue();

Similarly, we have methods for the other seven wrapper classes: byteValue(), shortValue(), longValue(), floatValue(), doubleValue(),
charValue(), booleanValue().
Auto boxing and auto unboxing

Creating a wrapper class object using the constructors and retrieving the values wrapped by those objects using the methods as
shown above can become quite cumbersome. As an alternative, there exists auto boxing and uutounboxing. Auto boxing refers to
an implicit call to the constructor and auto unboxing refers to an implicit call to the *value() method. Therefore, a new wrapper object
can be created by specifying the value to be wrapped just as we would do for a primitive data type variable. Also, the value can be
retrieved and used in a simple way by specifying the object name. Look at the following code:

Integer intObject = 34;


int x=intObject;
int x = intObject + 7;

The above statements are equivalent to the following set of statements

Integer intObject = new Integer (34);


int x = intObject.intValue();
int x = intObject .intValue()+ 7;

Similarly, auto boxing and auto boxing apply to other wrapper classes also.

Conversion between data types

The wrapper classes also provide methods which can be used to convert a String to any of the primitive data types, except
character. All these methods are static. These methods have the format parse*() where * refers to any of the primitive data types
except char. And to convert any of the primitive data type value to a String, we use the valueOf() methods of the String class which
through method overloading and implicit casting can accept any of the eight primitive types.

int x = Integer.parseInt("34"); // x=34


double y = Double.parseDouble("34.7"); // y =34.7
String s1= String.valueOf('a'); // s1="a"
String s2=String.valueOf(true); // s2="true"

Wrapper classes allows us to convert the primitive types into an object type.
java is not 100% object oriented programming language because of the 8 primitive types. Then wrapper classes are introduced to
give the primitive types an object form. So the primitive types can also be stored as an object of its respective wrapper class
The 8 primitive types and its wrapper classes are,
byte. - Byte
int - Integer
short - Short
long - Long
float - Float
double - Double
char - Character
boolean - Boolean

all this wrapper classes are available in java.lang package


Now if you want to store an integer as an object type you can write it as
Integer i=new Integer(10);
This is known as Boxing, converting a primitive type into an object.
Now to get that integer value back,
int a=i.intValue();
This operation is known as Unboxing converting the value of a wrapper class object into a primitive type.
After java 1.5/5 Boxing and Unboxing became automatic. You can directly assign the primitive as an object of wrapper class.
Integer i=10;
Before java 1.5/5, databases stores only Object class objects so to store a primitive type into an ArrayList or Vector wrapper classes
are used. Primitive types are converted into wrapper class object through boxing and upcasted to Object type to store in the
database.

The significance of wrapper class comes when you want to write a program which will work with any type of value. To write such a
program declare the arguments as Object type since Object class is extended by all the other class in java Object class type can store
any kind of objects.
Lets take an example, you want to write a program which will work if you pass any kind of values
public static void printHello(Object a)
{
System.out.println("Hello");
}
This program will work with all kind of values. Since Object class is the super most class, Object type variable can accept any objects.
the wrapper class comea into picture when you pass a primitive type value. Imagine you are calling the function with a value 10
printHello(10);
Now the 10 will be boxed and becomes an object of Integer class(wrapper class) since Integer extends Object the method will work
fine.
There are many other uses which comes while overriding the build in methods like compare(), equals() etc because all these
functions have Object type as parameters.

The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is
known as unboxing. This is the new feature of Java5. So java programmer doesn't need to write the conversion code.

Advantage of Autoboxing and Unboxing:

No need of conversion between primitives and Wrappers manually so less coding is required.

Simple Example of Autoboxing in java:

1.
2. class BoxingExample1{
3. public static void main(String args[]){
4. int a=50;
5. Integer a2=new Integer(a);//Boxing
6.
7. Integer a3=5;//Boxing
8.
9. System.out.println(a2+" "+a3);
10. }
11. }
12.
Test it Now
Output:50 5
download this example

Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing. Let's see the example of
unboxing:

1.
2. class UnboxingExample1{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5. int a=i;
6.
7. System.out.println(a);
8. }
9. }
10.
Test it Now
Output:50

Autoboxing and Unboxing with comparison operators

Autoboxing can be performed with comparison operators. Let's see the example of boxing with comparison operator:
1.
2. class UnboxingExample2{
3. public static void main(String args[]){
4. Integer i=new Integer(50);
5.
6. if(i<100){ //unboxing internally
7. System.out.println(i);
8. }
9. }
10. }
11.
Test it Now
Output:50

Autoboxing and Unboxing with method overloading

In method overloading, boxing and unboxing can be performed. There are some rules for method overloading with boxing:
Widening beats boxing

Widening beats varargs

Boxing beats varargs


1) Example of Autoboxing where widening beats boxing

If there is possibility of widening and boxing, widening beats boxing.


1.
2. class Boxing1{
3. static void m(int i){System.out.println("int");}
4. static void m(Integer i){System.out.println("Integer");}
5.
6. public static void main(String args[]){
7. short s=30;
8. m(s);
9. }
10. }
11.
Test it Now
Output:int

2) Example of Autoboxing where widening beats varargs

If there is possibility of widening and varargs, widening beats var-args.


1.
2. class Boxing2{
3. static void m(int i, int i2){System.out.println("int int");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. short s1=30,s2=40;
8. m(s1,s2);
9. }
10. }
11.
Test it Now
Output:int int

3) Example of Autoboxing where boxing beats varargs

Let's see the program where boxing beats variable argument:


1.
2. class Boxing3{
3. static void m(Integer i){System.out.println("Integer");}
4. static void m(Integer... i){System.out.println("Integer...");}
5.
6. public static void main(String args[]){
7. int a=30;
8. m(a);
9. }
10. }
11.
Test it Now
Output:Integer

Method overloading with Widening and Boxing

Widening and Boxing can't be performed as given below:


1.
2. class Boxing4{
3. static void m(Long l){System.out.println("Long");}
4.
5. public static void main(String args[]){
6. int a=30;
7. m(a);
8. }
9. }
10.
Test it Now
Output:Compile Time Error

Вам также может понравиться