Converting a String to Integer in Java

In this example you will learn how to use the Converting a String to Integer in Java

Converting a String to Integer in Java

In this example you will learn how to use the Converting a String to Integer in Java

Converting a String to Integer in Java

Converting a String to Integer in Java

In this video tutorial I will show you how to convert a String value to Integer in Java?

The easiest way to convert a String to Integer is to use the Integer class and then call the parseInt method. There are two methods of converting the String into integer value. One method is to use the Integer.parseInt() method which returns the primitive int value.

Second method returns the object of Integer class and this we have to use the Integer.valueOf() method of the Integer class. Based on your requirement you can use any of the method in your program. These two method also throws the exception if it is not able to convert the supplied string into Integer, so you should also handle the exception correctly in your code.

In the video tutorial I have explained the steps to run this conversion program in Eclipse.

Here is the video tutorial of "How to convert String to Integer in Java?":

Here is example code for converting a string to Integer:


String strNoOfItems = "1000";
  int items = Integer.parseInt(strNoOfItems);
  

Application will also throw exception if it is not able to convert the String to Integer. This function throws NumberFormatException in case the input String is not contains parsable integer value.

The second method is to use the valueOf() method of the Integer class. This method is also static and can be used following way:

String strNoOfItems = "1000";
  Integer items = Integer.valueOf(strNoOfItems);
  

This method is returning an instance of java.lang.Integer class. So,

parseInt - returns the premitive int value
valueOf - returns an instance of java.lang.Integer class

Handling the exception while converting String to Integer:

If program is not able to convert the input string to Integer it throws NumberFormatException. Following example shows how to handle the exception:

String strNoOfItems = "200Test1000";
  Integer items = null;
  try{
  items = Integer.valueOf(strNoOfItems);
  }catch (NumberFormatException e) {
  //Error handling code
System.out.println("Error is: " + e.getMessage()); }

Check more related tutorial in Java programming section.