Sunday, September 6, 2009

Convert String to integer (int) in Java

Java Code Online will discuss the Java Code to convert a String to an int. There is a feature provided in Java, which helps to perform this operation. The conversion is done with the help of a method called parseInt().

Actually any String which could be converted to a primitive can be converted to it, by using the parseXxx() method, where Xxx will replace the type in which it is to be converted, like int, float, etc.

I have provided a sample Java Code which asks the user to enter a number, which is taken as a String by the application. Later it is converted to an integer by using the parseInt() method. Go through the code for a clear understanding on how it is to be used.

  package developer;

  import java.util.Scanner;

  public class StringToInt {

  public static void main(String[] args) {

        System.out.println("Enter a number which would be taken as a String by the application");
        Scanner scanStr = new Scanner(System.in);
        String numStore = null;
        int numConvert = 0;

        // Takes the input as a String
        if (scanStr.hasNext()) {
            numStore = scanStr.next();
        }

        // Convert the String to int by using the Integer.parseInt() method
        numConvert = Integer.parseInt(numStore);

        System.out.println("The number entered by you is: " + numConvert);

     }
  }

The output is something like as shown below.


  Enter a number which would be taken as a String by the application
  22
  The number entered by you is: 22


Some observation points are:-
The String which is to be converted to a number must be a number in the String format. This is required so that the Java parser can parse the String successfully into an int.

If the value entered is not a number, suppose that you entered a String in words in place of a number in String format, then the output is shown below:-

 Enter a number which would be taken as a String by the application
 Conversion from String to int
 Exception in thread "main" java.lang.NumberFormatException: For input string: "Conversion"
     at java.lang.NumberFormatException.forInputString(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at java.lang.Integer.parseInt(Unknown Source)
     at developer.StringToInt .main(StringToInt .java:20)

So we see that if a String is entered to be parsed as an int, then the Java Compiler gives a big fat "NumberFormatException".

I hope the Java Code provide to convert an a String to an int was helpful. Do leave a comment if you liked the article. Java Code Online will soon be back with another interesting Java article.

Related Java Codes:-
Convert int to String in Java
Convert int to String in Java using Wrapper Classes

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.