Learn Java: Java Q&A: How do I convert a String to an int?
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


Question: How do I convert a String to an int with Java?
Answer:  

The Integer class includes a method named parseInt() that serves just this purpose. An example of a simple program that performs this conversion is shown below:

public class s2i {

   public static void main (String[] args) {

      // String s = "fred";    // do this if you want an exception

      String s = "100";

      try {
         int i = Integer.parseInt(s.trim());
         System.out.println("int i = " + i);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());
      }

   }

}

Other notes

  • Integer.toString(int i) is used to convert in the other direction, from int to String.
     
  • If you're interested in converting a String to an Integer object, use the valueOf() method of the Integer class instead of the parseInt() method.

 


Read the BLOG

Copyright © 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.