Library contents

Java Integer.parseInt

Order forms supply text. Integer.parseInt converts a signed whole-number string into an int and reports malformed or out-of-range input with NumberFormatException.

A simple example

Integer.parseInt

  1. Start with "12"
  2. Do this Read a base-ten integer
  3. Result 12
The characters 1 and 2 represent one ten and two ones. The resulting number can be used in arithmetic.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Integer.parseInt("12"));
    }
}
Output
12

Syntax

Java syntax
Integer.parseInt(text, 10)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Detect an out-of-range shipment quantity

A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.

First output line42
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        for (String text : new String[]{"42", "2147483648", "42kg"}) {
            try {
                System.out.println(Integer.parseInt(text, 10));
            } catch (NumberFormatException ex) {
                System.out.println("invalid");
            }
        }
    }
}
Output
42
invalid
invalid

Parsing handles the numeric range. Separate business rules can still reject negative quantities. A trailing unit such as kg requires a separate parsing step.

Advertisements

Read the afternoon delivery

A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?

Given“18” + 2 on hand
Worked result20

Read an empty delivery count

A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?

Given“0” + 2 on hand
Worked result2

What to watch for

Parsing accepts negative integers. A separate business rule can require a positive quantity.

Documentation for Integer.parseInt