MainMenu

Home Java Overview Maven Tutorials

Thursday 17 October 2019

Wrapper class in Java

Wrapper in java



Wrapper Class In java






Wrapper Class In Java
before this , there is a question
Question :- Java is 100% Object Oriented Programing Language or not?
Answer :- Java is 99.9 % object Oriented Programming Language
It is not 100% Object Oriented Programing language , due to its primitive data Types :-
int, float , char, double etc..
These are derived from C and these are not objects
and 100% object oriented means that every thing should be in form of object.
and primitive data types are not object
for example :-
int data;
here data is not an object, it's a variable.

So in java , we have classes for every data types, we call the as wrapper classes,

Table for primitive data type and wrapper classes

>
Primitive TypeWrapper Class
booleanBOOLEAN
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
for example for int, we have class Integer
primitive int variable
int x = 20;
not if i want to convert this varibale into an object, then i have to write
Integer i = new Interger(x); OR Integer i = new Interger(20);
now i is 20;
This way of converting primitive into object is called as AutoBoxing

Now, how to take out value from Integer Object
Interger i = new Integer(20);
direct value can't be assigned to object so we need to use a method datatypeValue
int j = i.intValue();
now j = 10;
So getting the priitive value from object is called as Unboxing
public class Wrappractice
{
public static void main(String args[])
{
int i = 20;
Interger mydata = new Integer(i); //Autoboxing
System.out.println("value of i is " + i);
int j;
j = mydata.intValue();
System.out.println( "value od j is " +j); //Unboxing
}
}
--------------------------------------------------------

Wrapper class are Immutable in Java


All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.


Example to prove that wrapper classes are Immutable

public class Wrap
{
public static void main(String[] args)
{
Integer x = new Integer(20);
System.out.println("before modification value of x is :" +x);
add(x);
System.out.println("After modification value of x is :" +x);
}
public static void add(int x)
{
x = x+1;
System.out.println(x);
}
}


Output :-


before modification value of x is :20
21
After modification value of x is :20

Note : String isn't a primitive type.