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
- Start with "12"
- Do this Read a base-ten integer
- Result 12
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Integer.parseInt("12"));
}
}
12
Syntax
Integer.parseInt(text, 10)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDetect 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.
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");
}
}
}
}
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.
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?
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?
What to watch for
Parsing accepts negative integers. A separate business rule can require a positive quantity.