The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

Creating More Wrapper Objects

Some of the wrapper classes have a second constructor that takes a String as an argument and tries to convert to the appropriate type. For example:

    Integer i = new Integer ("17");
    Double d = new Double ("3.14159");

The type conversion process is not very robust. For example, if the Strings are not in the right format, they will cause a NumberFormatException. Any non-numeric character in the String, including a space, will cause the conversion to fail.

    Integer i = new Integer ("17.1");        // WRONG!!
    Double d = new Double ("3.1459 ");       // WRONG!!

It is usually a good idea to check the format of the String before you try to convert it.

Last Update: 2011-01-24