Convert of String to Integer or Integer to String in java

As a developer, in day to day programming, we have encountered in number of situations to convert from String to Integer or vice verse.

convertion of String to Integer:-

There are number way to convert from String to integer. For this, String should holds valid int value. if an invalid numeric value is presented in string, then NumberFormatException is thrown by parseInt method.For this, you have to handle using try and catch blocks

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

second way is to using parseInt method of Integer object To convert this to integer we have used Integer.parseInt method.

String s="123";
Integer i=Integer.parseInt(s);
and other way is using valueOf of 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);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.