Saturday, 7 April 2012

Converting Strings to Numbers in Java

To convert a String object to a primitive type you can use the following methods offered by the wrapper classes.



Wrapper
Static parseXxx() method
Byte
parseByte(String s)
parseByte(String s,int radix)
Short
parseShort(String s)
parseShort(String s,int radix)
Integer
parseInt(String s)
parseInt(String s,int radix)
Long
parseLong(String s)
parseLong(String s,int radix)
Float
parseFloat(String s)
Double
parseDouble(String value)
Character
None
Boolean
parseBoolean(String s)
Void
None


For example :

        byte b1 = Byte.parseByte("10");
        byte b2 = Byte.parseByte("10", 16);

        short s1 = Short.parseShort("15");
        short s2 = Short.parseShort("15", 2);

        int i1 = Integer.parseInt("20");
        int i2 = Integer.parseInt("20", 8);

        long l1 = Long.parseLong("100");
        long l2 = Long.parseLong("100", 8);

        float f1 = Float.parseFloat("3.14");

        double f2 = Double.parseDouble("3.14");

        boolean bool = Boolean.parseBoolean("false");



Notice that Byte,Short ,Integer and Long parseXxx() methods take an additional argument, int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented.

for example,

int i1 = Integer.parseInt("1001",2);

Here converts binary 1001 to the corresponding decimal value 9 and assigns the value 9 to variable i1.

java.lang.NumberFormatException

 

The parseXxx() methods throw java.lang.NumberFormatException when the given input string is invalid.For example

int i1 = Integer.parseInt("20f");
The above line throws a run-time exception,  java.lang.NumberFormatException: For input string: "20f".

No comments:

Post a Comment