Journal for Developers

How to convert Java String to Integer

0 125

Notice: Undefined index: rate in /home/content/p3pnexwpnas11_data03/84/3795084/html/wp-content/themes/publisher/includes/functions.php on line 5360
2 min read

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.

Subscribe to our Journal

Join our mailing list to receive the latest news and updates from our team.

You have Successfully Subscribed!