Showing posts with label Integer.valueOf. Show all posts
Showing posts with label Integer.valueOf. Show all posts

Tuesday, 21 January 2014

Java convert string to int value

Java provides two method parseInt() and valueOf() method to convert string into integer. Below example shows the usage of two methods to convert string to integer.

public class StringtoNumber {

public static void main(String[] args) {
String String1 = "000456";
  try{
  // using Integer.parseInt method
       int intvalue = Integer.parseInt(String1);
       System.out.println("With parseInt method, intvalue = " + intvalue );
        } catch(NumberFormatException e) {
        System.err.println("NumberFormatException in parseInt, "+ e.getMessage());
        }
         
        try{
        // using Integer.valueOf method
             int intvalue = Integer.valueOf(String1);
             System.out.println("With valueOf method, intvalue = " + intvalue );
             
          } catch(NumberFormatException e) {
              System.err.println("NumberFormatException in valueOf, "+ e.getMessage());
        }
     }
}

Output -
      With parseInt method, intvalue = 456

      With valueOf method, intvalue = 456

Note - Catch section gets executed in case, Java fails to convert string to integer.