Monday, December 10, 2012

Understand Wrapper and parse !!!


Practically Wrapper mean wrap the primitive in different value, so that we can use it as per the situation. 

There is wrapper class for every primitive in java. The wrapper class for int is Int, float is Float, char is Character, byte is Byte, double is Double and so on.


                Integer int1 = new Integer("4");
Integer int2 = new Integer("1");
Double int3 = new Double(123.12);

i = int2 + int1;
System.out.println(i);        //5


When we convert the value of wrapped numeric to a primitive than we use following value() methods. That mean we put byteValue(), doubleValue() and so on. 

byte b = int1.byteValue();
System.out.println(b);           

short s = int3.shortValue();
System.out.println(s);

double d = int2.doubleValue();
System.out.println(d);


Following example show the created value of int4 is 5, cause when you convert binary of 101 than you will get 5. So int = 5 now. This is called valueOf() method.

Integer int4 = Integer.valueOf("101",2);
System.out.println(int4);  


Now we look on some parseXxx()  method, it is nearly like valueOf() method.
Following example is for converting string to other primitive what ever you like to apply.


               double d1 = Double.parseDouble("789.456");
System.out.println(d1);


               long l1 = Long.parseLong("101",2);
System.out.println(l1);

Now above example is same like we apply in valueOf() methos, we get same output but using different method.

        

Now when we use toXxxString() method than it convert the following:



                String s1 = Integer.toHexString(123);  
System.out.println(s1);                             // 7b

String s2 = Long.toOctalString(123);
System.out.println(s2);                              //173

String s3 = Double.toHexString(789);
System.out.println(s3);                             //0x1.8a8p9




Now toString(), in this method you can convert every primitive values to string:


               Long l = new Long("789456123");
System.out.println(l.toString());        //789456123

String l2 = Long.toString(789456123);


You can take different primitive value.





No comments:

Post a Comment