Академический Документы
Профессиональный Документы
Культура Документы
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;
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.
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
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;
7. //compareTo demo
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;
14. }
15. }
Output
Summary
Wrapper class provides many methods while using collections like sorting, searching etc.
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.
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:
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:
Similarly, auto boxing and auto boxing apply to other wrapper classes also.
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.
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
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.
No need of conversion between primitives and Wrappers manually so less coding is required.
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
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 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
In method overloading, boxing and unboxing can be performed. There are some rules for method overloading with boxing:
Widening beats boxing