Conversions

ParseInt

🙋 Need help? Ask an expert now!

In Java, the Integer class is part of the java.lang package and is automatically imported just like the String class. The parseInt() method is part of the Integer class. This method converts a String that only consists of numbers into an integer value while simultaneously assigning it to the primitive data type int. The syntax for this method is as follows, Integer.parseInt(stringname). Let's see how this method works in the code below.

ParseIntExample.java
package exlcode;

public class ParseIntExample {

  public static String exampleVariableOne = "5666";
  public static String exampleVariableTwo = "423";
  public static int exampleVariableThree = Integer.parseInt(exampleVariableOne);
  public static int exampleVariableFour = Integer.parseInt(exampleVariableTwo);

  public static void main(String[] args) {
    System.out.println("Integer exampleVariable of exampleVariableOne is " + exampleVariableThree);
    System.out.println("Integer exampleVariable of exampleVariableTwo is " + exampleVariableFour);
  }
}

The parseInt() method returns an int, not an object from the Integer class. This method only works if the String consists solely of numbers and no characters. If that is not the case, an error will be thrown and an integer will not be created.

The parseInt() function is extremely useful when dealing with user input or calculating numbers from text files. With this method, Java is saving the programmer time from creating long methods to convert strings into integers, by having an included parseInt() method.

Application Question

Which of the statements below is correct?