This example shows how to convert String to wrapper objects Integer, Long, Float, Double, Byte, and Short object.
How to convert String to wrapper objects in Java?
There are a couple of methods using which a string can be converted to wrapper class objects.
1) Using a wrapper class constructor
All wrapper classes provide a constructor that accepts a string as an argument and returns the respective wrapper object. You can use this constructor to convert as given in below example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.javacodeexamples.basic.wrapperclasses; public class StringToWrapperExample { public static void main(String[] args){ String strByte = "32"; Byte bObj = new Byte(strByte); System.out.println("String to Byte object: " + bObj); String strShort = "523"; Short sObj = new Short(strShort); System.out.println("String to Short object: " + sObj); String strInt = "5829"; Integer iObj = new Integer(strInt); System.out.println("String to Integer object: " + iObj); String strLong = "954342"; Long lObj = new Long(strLong); System.out.println("String to Long object: " + lObj); String strFloat = "43.53"; Float fObj = new Float(strFloat); System.out.println("String to Float object: " + fObj); String strDouble = "94322.2321"; Double dObj = new Double(strDouble); System.out.println("String to Double object: " + dObj); } } |
Output
1 2 3 4 5 6 |
String to Byte object: 32 String to Short object: 523 String to Integer object: 5829 String to Long object: 954342 String to Float object: 43.53 String to Double object: 94322.2321 |
2) Convert using the valueOf method of a wrapper class
You can use the valueOf
static method of a respective wrapper class to convert from string to any wrapper class object as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
String strByte = "32"; Byte bObj = Byte.valueOf(strByte); String strShort = "523"; Short sObj = Short.valueOf(strShort); String strInt = "5829"; Integer iObj = Integer.valueOf(strInt); String strLong = "954342"; Long lObj = Long.valueOf(strLong); String strFloat = "43.53"; Float fObj = Float.valueOf(strFloat); String strDouble = "94322.2321"; Double dObj = Double.valueOf(strDouble); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.