✏️ Explanatory Question
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:
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
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
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);
}
}
If you are reading data from files, APIs, or databases that return numeric values as strings, parseInt() helps convert them.
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!");
}