Converting a String to a Wrapper Object

Converting a String to a Wrapper Object is a requirement some times you come across in project development.

Let say you have String variable holding a value "25", and now you need to convert this to a Wrapper Object.

There are two ways to do it.

1. Make an object of Wrapper using the constructor

String s="25";
Integer i=new Integer(s);

2. Use the method valueOf().

There are two versions of valueOf(), both takes String as parameter and converts it to the Wrapper, the other versions also allows you to pass the binary or octal or hexadecimal representation of the String and convert it to the Wrapper object.

For class Integer , the method valueOf() looks like

public static Integer valueOf(String s) throws NumberFormatException

public static Integer valueOf(String s,int radix) throws NumberFormatException

String s="25";
Integer i=Integer.valueOf(s);

Let say you have String like "10101" which is binary representation of number 21.

String s="10101";
Integer i=Integer,valueOf(s,2);

Here 2 represents that the given String has to converted from binary to decimal. If we pass 8 in place of 2, conversion will be octal and if we pass 16 then conversion will be hexadecimal.


Post a Comment