Home / Questions / When parseInt() method can be used?
Explanatory Question

When parseInt() method can be used?

👁 716 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

In Java, the parseInt() method is used to convert a string into an integer. It belongs to the Integer class and is part of the java.lang package. You can use it in the following scenarios:

1. Converting a Numeric String to an Integer

If you have a number stored as a string and need to convert it into an integer:


String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // Output: 123

2. Converting a String with a Specific Radix (Base)

You can specify a radix (base) to convert numbers in different numeral systems:


String binaryStr = "1010";
int num = Integer.parseInt(binaryStr, 2); // Binary to Decimal
System.out.println(num); // Output: 10

Example for hexadecimal:


String hexStr = "A";
int num = Integer.parseInt(hexStr, 16); // Hex to Decimal
System.out.println(num); // Output: 10

3. Handling Input from the User

If the user enters a number as a string (e.g., via Scanner), you can convert it to an integer:


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input = scanner.nextLine();
        int number = Integer.parseInt(input);
        System.out.println("You entered: " + number);
    }
}

4. Extracting Integer Values from External Sources

If you are reading data from files, APIs, or databases that return numeric values as strings, parseInt() helps convert them.

5. Handling Exceptions

If the input string is not a valid integer, parseInt() throws a NumberFormatException, so it’s good practice to handle it:


try {
    int num = Integer.parseInt("abc"); // Invalid input
} catch (NumberFormatException e) {
    System.out.println("Invalid number format!");
}