Java String Conversions
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:
String str1 = String.valueOf(10); // right way to convert from an integer to String
Note that direct assignments or casts will result in compiler error, such as these two statements:
String str1 = 10; // compiler error—cannot convert from int to String String str1 = (String) 10; // compiler error—cannot convert from int to String
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:
int i = "10"; // compiler error—cannot convert from String to int int i = (int) "10"; // compiler error—cannot convert from String to int
To make this type conversion, you need to use the parseInt() static method available in the Integer class, like so:
int i = Integer.parseInt("10"); // right way to convert from a String to an int
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,
float f = Float.parseFloat("no such value");
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.
Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects
SILAN Technology, BBSR Call to: 9439202111 | 9658317757 | 0674-2361252