Convert String to different wrapper types and primitive data types in Java

In this post, we will see 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 this post.

 

2. Converting String to double (or Double)

We can use the Double.parseDouble() or Double.valueOf() method to get corresponding primitive double value or value of Double wrapper class respectively. If the string cannot be converted 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 corresponding primitive long value or value of Long wrapper class respectively. If the string is not a long, NumberFormatException will be thrown.

 

4. Converting String to boolean (or Boolean)

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

 

5. Converting String to Character Array

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

 

6. Converting String to Byte Array

We can convert a String to a byte array using 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 SimpleDateFormat class in Java which takes the pattern describing the date format. ParseException will be thrown if the string doesn’t match with the specified pattern in SimpleDateFormat. For more details, please refer this post.

 

 
Download Code
Run Code

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of