0
0
Javaprogramming~15 mins

Parsing numeric arguments in Java

Choose your learning style8 modes available
menu_bookIntroduction

Parsing numeric arguments means turning text input into numbers so the program can use them for math or decisions.

When reading numbers typed by a user in a program.
When getting numbers from command line arguments to control program behavior.
When loading numbers stored as text in files or databases.
When converting strings from web forms into numbers for calculations.
regular_expressionSyntax
Java
int number = Integer.parseInt(text);
double decimal = Double.parseDouble(text);

Use Integer.parseInt to convert text to whole numbers (int).

Use Double.parseDouble to convert text to decimal numbers (double).

emoji_objectsExamples
line_end_arrow_notchThis converts the text "25" into the number 25.
Java
int age = Integer.parseInt("25");
line_end_arrow_notchThis converts the text "19.99" into the decimal number 19.99.
Java
double price = Double.parseDouble("19.99");
line_end_arrow_notchThis converts the first command line argument into an integer.
Java
int count = Integer.parseInt(args[0]);
code_blocksSample Program

This program converts two strings into numbers and prints them.

Java
public class ParseExample {
    public static void main(String[] args) {
        String input1 = "123";
        String input2 = "45.67";

        int number = Integer.parseInt(input1);
        double decimal = Double.parseDouble(input2);

        System.out.println("Integer value: " + number);
        System.out.println("Double value: " + decimal);
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

If the text is not a valid number, parsing will cause an error (NumberFormatException).

line_end_arrow_notch

Always check or handle errors when parsing user input to avoid crashes.

list_alt_checkSummary

Parsing numeric arguments converts text into numbers for use in programs.

Use Integer.parseInt for whole numbers and Double.parseDouble for decimals.

Be careful to handle invalid input to keep programs safe.