Java Integer.parseInt() Method

The Java parseInt() method is a method of Integer class that belong to java.lang package. The parseInt() method in Java is crucial for converting string representations of numbers into actual integer values. This capability is fundamental in various programming scenarios, such as when numerical data comes in text form-through user input, data files, or external systems-and needs to be used for calculations, comparisons, or as part of the application's logic.

The conversion process is essential for handling numeric data correctly and efficiently, enabling developers to write more flexible, reliable, and powerful Java applications. By providing easy-to-use tools for working with different data types, Java helps bridge the gap between the often text-heavy world of data input/output and the numeric calculations central to software development.

There are the following three variants of parseInt() methods that can be differentiated depending on its parameter.

  1. parseInt (String s)
  2. parseInt (String s, int radix)
  3. parseInt(CharSequence s, int beginText, int endText, int radix)

Purpose of parseInt() Method

The parseInt() method in Java is used to change numbers that are written as text (strings) into actual numbers (integers) that the computer can understand and work with.

For example, if you have the text "149" and you want to add 3 to it, you first need to change "149" into a number. The following Java program demonstrate the same.

Filename: ParseIntExample.java

Output:

152

By using parseInt(), we can easily turn text into numbers, making it easier to do things like math operations. This method is really helpful when we are dealing with data that comes in as text but we need to use it as numbers, like user input or information from files.

Working of parseInt() Method

The parseInt() method in Java is designed to convert a string into an integer. Here's a step-by-step breakdown of how it works:

  1. Input String: The method starts by taking a string that we want to convert into an integer. This string should ideally represent a numerical value.
  2. Checking the Sign: It looks at the first character of the string to figure out if the number is positive or negative. It is done by checking for a '+' (plus) or '-' (minus) sign.
  3. Ignoring the Sign: If there's a sign, the method notes it but then ignores it for the next steps, focusing only on the numerical part of the string.
  4. Converting Characters to Numbers: The method goes through the string character by character, starting from the left (or right after the sign if there was one). Each numerical character (like '2' or '7') is converted into its integer equivalent (2 or 7).
  5. Handling Invalid Characters: If the method finds a character that isn't a number (like a letter 'a' or a symbol '&'), it stops and throws an error because the string can't be turned into a pure number.
  6. Building the Integer: As it converts each character, the method builds the final integer. It does this by taking each digit, starting from the left, and adding it to the total, adjusting for its position (tens, hundreds, etc.).
  7. Returning the Result: Once all characters have been processed and the total integer value is built, this number is returned. If the initial sign was negative, the method makes sure the final result is negative too.

This process allows the parseInt() method to accurately convert a string representation of a number into an actual integer value, ready to be used for mathematical operations and other purposes where a numerical value is required.

Advantages of the parseInt() Method

The parseInt() method in Java offers several advantages that make it a useful tool for developers. Here are some of the key benefits:

  1. Converts Strings to Integers: It enables the conversion of string representations of numbers into integer values, which is essential for performing arithmetic operations and logical comparisons in programs.
  2. Supports Various Number Bases: With the parseInt(String s, int radix) variant, it can parse strings representing numbers in different bases (from binary to hexadecimal and beyond), providing flexibility in handling numerical data encoded in various numeral systems.
  3. Facilitates Data Parsing: It is particularly useful in scenarios involving data parsing from user inputs, files, or network responses, where numeric data is often received as strings.
  4. Error Handling: It throws a NumberFormatException when the input string cannot be parsed into an integer. This exception mechanism helps in validating input data and implementing robust error handling, ensuring that programs can deal with invalid input gracefully.
  5. Improves Performance: Converting string representations of numbers into their integer equivalents is optimized in Java, making the parseInt() method efficient and suitable for performance-sensitive applications.
  6. Simplifies Code: Using parseInt() simplifies code by abstracting the complexity of manual number parsing. Developers can focus on core logic without worrying about the details of converting string data into integers.
  7. Integral Part of Java's Standard Library: Being part of the standard lang package, it is readily available and does not require any additional libraries or frameworks, ensuring compatibility and ease of use across different Java applications.
  8. Strong Type Safety: By converting strings to integers, it reinforces Java's strong type system, allowing developers to work with well-defined data types and leverage Java's compile-time type checking.

Syntax of parseInt() Method

Following are the declarations of parseInt () method:

Parameter:

DataTypeParameterDescriptionRequired/Optional
StringsIt is a String which needs to be converted into the Integer equivalent.Required
intradixThe radix to be used while parsing the StringRequired
intbeginIndexThe beginning index, inclusive.Required
intendIndexThe ending index, exclusive.Required
CharSequencesIt is the CharSequence which needs to be converted into the Integer equivalent.Required

Returns:

MethodReturns
parseInt (String s)This method returns the integer value which is represented by the argument in decimal equivalent.
parseInt (String s, int radix)This method returns the integer value which is represented by the string argument in the specified radix.
parseInt (String s, int radix)This method returns the integer value which is represented by the string argument in the specified radix.

Exceptions:

NullPointerException: If s is null.

IndexOutOfBoundsException: If beginIndex is negative, or if beginIndex is greater than endIndex or if endIndex is greater than s.length ().

NumberFormatException: If the CharSequence does not contain a parsable int in the specified radix, or if radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.

Compatibility Version:

Java 1.2 and above:

  • parseInt (String s)
  • parseInt (String s, int radix)

Java 9:

  • parseInt (CharSequence s, int beginText, int endText, int radix)

1. Java Integer parseInt (String s) Method

This method parses the String argument as a signed decimal integer object. The characters in the string must be decimal digits, except that the first character of the string may be an ASCII minus sign '-' to indicate a negative value or an ASCII plus '+' sign to indicate a positive value. It returns the integer value which is represented by the argument in a decimal integer.

Syntax:

Filename: ParseIntExample.java

Output:

The string converted to integer is: 1234
After adding 100 to the converted integer: 1334

2. Java Integer parseInt (String s, int radix) Method

This method parses the String argument as a signed decimal integer object in the specified radix by the second argument. The characters in the string must be decimal digits of the specified argument except that the first character may be an ASCII minus sign '-' to indicate a negative value or an ASCII plus sign '+' to indicate a positive value. The resulting integer value is to be returned.

Syntax:

Filename: ParseIntRadixExample.java

Output:

ParseIntRadixExample

3. Java Integer parseInt (CharSequence s, int beginText, int endText, int radix)

This method parses the CharSequence argument as a signed integer in the specified radix argument, beginning at the specified beginIndex and extending to endIndex - 1. This method does not take steps to guard against the CharSequence being mutated while parsing.

Syntax:

Filename: ParseIntCharSequenceExample.java

Output:

The parsed integer is: 43981

Example 1

Filename: IntegerParseIntExample1.java

Test it Now

Output:

Value = 20
Value = 20
Value = -20

Example 2

Filename: IntegerParseIntExample2.java

Test it Now

Output:

Value = 104
Value = 512
Value = -484

Example 3

Filename: IntegerParseIntExample3.java

Test it Now

Output:

200100
300

Example 4

Filename: IntegerParseIntExample4.java

Test it Now

Output:

int i = 100

Example 5

Filename: IntegerParseIntExample5.java

Test it Now

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "10A"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at myPackage.IntegerParseIntExample5.main(IntegerParseIntExample5.java:6)

Overall, the parseInt() method is a powerful utility for processing and manipulating numeric data within Java applications, offering a combination of flexibility, efficiency, and robustness.