Write a Java Program to convert string type variables into int

In Java, you can convert a string variable into an integer variable using the parseInt() method.

This method belongs to the Integer class and is a static method, which means you can call it without creating an instance of the class.


Here’s an example of how to use the parseInt() method to convert a string variable str into an integer variable num:

String str = "123";
int num = Integer.parseInt(str);

In the above code, the parseInt() method takes the string str as its parameter and returns an integer value, which is then assigned to the variable num.

It’s important to note that if the string variable is not a valid integer, the parseInt() method will throw a NumberFormatException.

For example, if you try to convert the string "abc" into an integer, the following code will throw an exception:

String str = "abc";
int num = Integer.parseInt(str); // throws NumberFormatException

To avoid this, you can wrap the parseInt() method in a try-catch block to handle the exception.

Here’s an example:

String str = "abc";
int num;

try {
    num = Integer.parseInt(str);
} catch (NumberFormatException e) {
    System.out.println("The string is not a valid integer.");
    num = 0; // default value
}

In the above code, the parseInt() method is wrapped in a try-catch block.

If the string str is not a valid integer, the NumberFormatException will be caught and the message “The string is not a valid integer.” will be printed to the console.

The variable num is also assigned a default value of 0.


In summary, converting a string variable into an integer variable in Java is easy using the parseInt() method.

Just make sure to handle any potential NumberFormatException exceptions that may be thrown.