Friday, August 9, 2013

Wrapper Classes – I.




Java languages have eight primitive data types but primitive data types are not objects and they not belongs to any class. Often a primitive data type need to converted into a objects and wrapper wraps the around the data type to give an object effect. In some cases we cannot use primitive data type, so we need wrapper classes. For example, we need a wrapper class when we want to store number as a collection.

Data Type
Wrapper class
Uses
Remark
int
Integer
intValue()
Compare two Integer objects as numeric.
long
Long
longValue()
Returns value of Integer as  long.
float
Float
floatValue()
Returns the value of Integer as float.
double
Double
doubleValue()
Returns value of Integer as a double.
short
Short
shortValue();
Returns value of Integer as a short.
char
Character
Character CharObj = new Character(ch);
wrap primitive data type char value in an object
byte
Byte
byteValue()
Returns value of Integer as a byte.
boolean
Boolean
boolean equals(Object int_Obj)
Returns true if the Integer object is equivalent to int_Obj, or else returns false.

Parsing is to read the value of one object to convert it to another type. The parses method is used to get the primitive data type from a String 'parse' or convert strings into numbers.

Example:

parseInt(str)        Rreturns a signed decimal integer value that equivalent to String str.
parseDouble(str)  Rreturns a signed decimal double value that equivalent to String str.
parseFloat(str)     Rreturns a signed decimal Float value that equivalent to String str.
toString(int)        Rreturns a String object from an integer.

A float has 32 bits, and a double 64. doubles have higher precision than ints and floats.

Example:

import java.io.*;
class Parse_test
    {
            public static void main(String args[]) throws IOException
                {
                    BufferedReader Br=new BufferedReader(new InputStreamReader(System.in));
                    int Inum;
                    double Dnum;
                    float Fnum;
                    System.out.print("\tEnter an Integer Value : ");
                    Inum=Integer.parseInt(Br.readLine());
                    System.out.print("\tEnter an Double Value : ");
                    Dnum=Double.parseDouble(Br.readLine());
                    System.out.print("\tEnter an Float No. : ");
                    Fnum=Float.parseFloat(Br.readLine());
                    System.out.println("\n\tInteger Value : "+Inum);
                    System.out.println("\n\tDouble Value : "+Dnum);
                    System.out.println("\n\tFloat Value : "+Fnum);
                }
   }
                       

No comments: