Sunday, December 4, 2011

Convert of String to Integer or Integer to String in java

Convert String to Integer or Integer to String in java
As a developer, in the day to day programming, we have encountered in a number of situations to convert from String to Integer or vice verse.
String object holds a sequence of characters
Integer object stores the numeric values.
The string should hold valid int value. if an invalid numeric value is presented in the string, then NumberFormatException is thrown. For this, you have to handle using try and catch blocks.

How to Convert String to Integer in Java

There is a number way to convert from String to integer. For this,

Using Constructor 

one way is to create an Integer object which has Constructor of String type. This conversion happens at object creation.
String s="123";
Integer i=new Integer(s);

Using Integer.parseInt() method

Integer class has a parseInt method of Integer object To convert this to integer we have used Integer.parseInt method.
String s="123";
Integer i=Integer.parseInt(s);

using valueOf() method

another way is using valueOf of the Integer object
String s="123";
Integer i=Integer.valueOf(s);
Exception Handling:-
String s = "abc";
try {
Integer ii = Integer.valueOf(s);
} catch (NumberFormatException e) {
System.out.println("Invalid integer value in String " + s
     + "exception=" + e);

How to Convert Integer to String in Java? 

We can convert to String method using append empty string. Add an integer to empty string using plus operator and returns the string

Integer i=123;
String s=""+i;

Related article