Ticker

6/recent/ticker-posts

JAVA Wrapper classes With Example

Wrapper classes 

Wrapper classes are used to convert any primitive type into an object. The primitive data types are not objects, they do not belong to any class, they are defined in the language itself. While storing in data structures which support only objects, it is required to convert the primitive type to object first, so we go for wrapper class. Wrapper classes are used to convert any data type into an object. 

Premitive data type  Wrapper class
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean Boolean

As you can observe in the above hierarchy, the super class of all numeric wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper classes are defined as final and thus designers prevented them from inheritance 

Number class is an abstract class. It has some following methods 
byte byteValue() this method converts calling object into byte value 
short shortVlaue() 
int intValue() 
long longValue() 
folat floatValue() 
double doubleValue() 

Boxing and unboxing in java 

Boxing, otherwise known as wrapping, is the process of placing a primitive type within an object so that the primitive can be used as a reference object 

Auto-boxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on 

Un-boxing is a process by which the value of object is automatically extracted from a type wrapper 

        Integer i = 100; //autoboxing 

        int j = i; //unboxing 

Parsing in java 

Parsing is to read the value of one object to convert it to another type. For example you may have a string with a value of "10". Internally that string contains the Unicode characters '1' and '0' not the actual number 10. The method Integer.parseInt takes that string value and returns a real number. 

public class ParsingPrg 

        public static void main(String[] args) 
        
                 String s1 = "80"; 
                 String s2 = "90"; 
                 int i = Integer.parseInt(s1); 
                int j = Integer.parseInt(s2); 
                System.out.println(i+" + "+j+" = "+i+j); 
        
 }