HomeJavaHow to convert Java String to Integer

How to convert Java String to Integer

Most of the times developers are looking for the solution to convert java string to integer data type in java. In this journal entry, we will be talking about how we can convert a Java String to Integer data type.

Convert Java String to Integer

Solution to the problem is to use the parseInt method of the Java Integer class. The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

#Example

public class JavaStringToIntExample
{
  public static void main (String[] args)
  {
    // String s = "fred";  // use this if you want to test the exception below
    String s = "100";
 
    try
    {
      // the String to int conversion happens here
      int i = Integer.parseInt(s.trim());
 
      // print out the value after the conversion
      System.out.println("int i = " + i);
    }
    catch (NumberFormatException nfe)
    {
      System.out.println("NumberFormatException: " + nfe.getMessage());
    }
  }
}

 

Looking at the example above, the Integer.parseInt(s.trim()) method is used to change from the string s to the integer i in this line of code:

int i = Integer.parseInt(s.trim());

If the attempt to change fails ā€“ the Integer parseInt process will throw a NumberFormatException, which you must handle in a try/catch block.

Itā€™s not essential to use the String class trim() method but in a real-world program, you must use it as a best practice.

Here are a few related notes about the String and Integer classes:

  • Integer.toString(int i) is used to convert in the further direction, that is from an int to a Java String.
  • If youā€™re concerned with converting a String to an Integer object, use the valueOf() method of the Integer class instead of the parseInt() method.
  • If you need to convert strings to additional Java primitive fields,Ā use methods like Long.parseLong(), and so on.
RELATED ARTICLES

Most Popular