This post will discuss how to convert string in Java to different wrapper types and primitive data types supported by Java.

1. Converting string to int (or Integer)

We can use the Integer.parseInt() to get the corresponding primitive int value of a string or use Integer.valueOf() to get the corresponding value of Integer wrapper class. If the string is not an integer, NumberFormatException will be thrown. For more details, please refer to this post.

2. Converting string to double (or Double)

We can use the Double.parseDouble() or Double.valueOf() method to get the corresponding primitive double value or value of Double wrapper class, respectively. If it cannot convert the string to a double, NumberFormatException will be thrown.

3. Converting string to long (or Long)

We can use the Long.parseLong() or Long.valueOf() method to get the corresponding primitive long value or value of Long wrapper class, respectively. If the string is not long, NumberFormatException will be thrown.

4. Converting string to boolean (or Boolean)

We can use the Boolean.parseBoolean() or Boolean.valueOf() method to get the Boolean value represented by the specified string. The method returns a true value if the specified string is equal to “true” (case ignored) and returns false otherwise.

5. Converting string to Character array

To convert a string to a character array, we can use the toCharArray() method, as shown below:

6. Converting string to Byte Array

We can convert a string to a byte array using the getBytes() method, which encodes the string into a sequence of bytes using the platform’s default charset.

7. Converting string to java.util.Date

We can convert a string to java.util.Date datatype using the SimpleDateFormat class in Java, which takes the pattern describing the date format. ParseException will be thrown if the string doesn’t match the specified pattern in SimpleDateFormat. For more details, please refer to this post.

That’s all about converting strings to different wrapper types and primitive data types in Java.

 
Download Code
Run Code