In your programs, you’ll find it is often necessary to convert strings to and from primitive types such as floats, ints, and booleans. To convert from a primitive type value to String type, you can use the overloaded valueOf() method from the String class.
Let's start with converting an integer value 10 to String. Here’s how to do it:
Note that direct assignments or casts will result in compiler error, such as these two statements:
How about the conversion the other way around: if a string has value of some primitive type (say an integral value), how can you perform the conversion? Obviously, the following two statements, which attempt to directly assign or change type through an explicit cast, will result in compiler errors:
To make this type conversion, you need to use the parseInt() static method available in the Integer class, like so:
This parseInt() method is an overloaded method. There is another parseInt() method that takes an additional argument: the base (or radix) of the integral value such as octal and hexadecimal. The wrapper classes Byte, Short, Long, Float, and Double have the equivalent parse methods to convert a string to the corresponding primitive type value. What if you pass an invalid argument to one of these parse methods? For example,
For this code, you'll get a runtime exception of java.lang.NumberFormatException since the string "no such value" cannot be converted to float type value.❮ Previous Next ❯