How to convert String to integer and integer to String in Java?
The input user enters via textfield or textarea is always in the string format. You often need this input in the integer form. For example – age, mobileNo etc. To make the conversion easy from string to integer or integer to string, Java provides some useful and easy to use methods.
Convertion Of String To Integer In Java:
There are two methods available in java to convert string to integer. One is Integer.parseInt() method and another one is Integer.valueOf() method. Both these methods are static methods of java.lang.Integer class. Both these methods throw NumberFormatException if input string is not a valid integer. The main difference between Integer.parseInt() and Integer.valueOf() method is that parseInt() method returns primitive int where as valueOf() method returns java.lang.Integer object.
Convertion Of Integer To String In Java:
You are also often need to do the reverse conversion i.e converting from integer to string. Java provides couple of methods to do that also. one is Integer.toString() method and another one is String.valueOf() method. Both these methods return string representation of the given integer.