Java Integer parseInt() example

In this guide, you will learn about the Integer parseInt() method in Java programming and how to use it with an example.

1. Integer parseInt() Method Overview

Definition:

The parseInt() method of the Java Integer class converts a string representation of an integer to a primitive int value.

Syntax:

1. Integer.parseInt(String s)
2. Integer.parseInt(String s, int radix)

Parameters:

String s: The string representation of the integer to be parsed.

int radix: The base of the numeral system to be used for parsing the string (optional parameter, default is 10).

Key Points:

- Throws NumberFormatException if the provided string is not a valid representation of an integer.

- By default, the method parses the string as a base-10 integer. However, if you provide a radix, it can parse the string in different numeral systems, such as binary (base-2), octal (base-8), or hexadecimal (base-16).

- White spaces at the beginning or end of the string can lead to NumberFormatException.

2. Integer parseInt() Method Example

import java.util.Arrays;
import java.util.List;

public class ParseIntExample {
    public static void main(String[] args) {
        String number = "12345";

        // Parse string in base 10 (default)
        int parsedNumber = Integer.parseInt(number);
        System.out.println("Parsed integer (base 10): " + parsedNumber);

        // Parse string in different bases
        List<String> numbers = Arrays.asList("1011", "64", "FF");
        List<Integer> radixes = Arrays.asList(2, 8, 16);

        for (int i = 0; i < numbers.size(); i++) {
            int result = Integer.parseInt(numbers.get(i), radixes.get(i));
            System.out.println("Parsed integer (base " + radixes.get(i) + "): " + result);
        }

        // Try parsing an invalid string
        try {
            int invalidParsedNumber = Integer.parseInt("ABC");
        } catch (NumberFormatException e) {
            System.out.println("Error parsing 'ABC': " + e.getMessage());
        }
    }
}

Output:

Parsed integer (base 10): 12345
Parsed integer (base 2): 11
Parsed integer (base 8): 52
Parsed integer (base 16): 255
Error parsing 'ABC': For input string: "ABC"

Explanation:

In the example, we started by parsing the string "12345" using the default base 10 method. 

We then parsed three different strings using various bases. The string "1011" was parsed as binary (base-2), "64" as octal (base-8), and "FF" as hexadecimal (base-16). 

Lastly, we attempted to parse an invalid string "ABC" without specifying a base, which led to a NumberFormatException.

Comments