Java String to int

In Java, you can convert a String to an int using either the parseInt() method of the Integer class or the valueOf() method. Here’s how to do it:

1. Integer.parseInt()

The Integer.parseInt() method converts a String to an int directly. If the String is not a valid integer, it throws a NumberFormatException.


public class StringToIntExample {
    public static void main(String[] args) {
        String str = "12";
        
        // Convert string to int using parseInt
        int num = Integer.parseInt(str);
        
        System.out.println("Converted int: " + num);
    }
}

Output:
Converted int: 12

Code Explanation:

1. Integer.parseInt(str) takes the string str and converts it to an integer.

2. If the string is not a valid integer (e.g., “abc”), it will throw a NumberFormatException.

2. Integer.valueOf()

The Integer.valueOf() method also converts a String to an Integer object, but it returns an Integer object, not a primitive int. This can be useful if you need to work with Integer objects (for example, if you need to use collections like ArrayList)

Example:


public class StringToIntExample {
    public static void main(String[] args) {
        String str = "45";
        
        // Convert string to Integer using valueOf
        Integer num = Integer.valueOf(str);
        
        System.out.println("Converted Integer: " + num);
    }
}

Output:

Converted Integer: 45

Code Explanation:

1. Integer.valueOf(str) converts the string str to an Integer object.

2. You can then use this Integer object like any other object, or convert it back to a primitive int using intValue().

How to Handle Exceptions?

Both parseInt() and valueOf() throw a NumberFormatException if the string cannot be converted to a valid integer. You should handle this exception to prevent your program from crashing.

Example


public class StringToIntExample {
    public static void main(String[] args) {
        String str = "ab";  // Invalid number string
        
        try {
            int num = Integer.parseInt(str); // This will throw NumberFormatException
            System.out.println("Converted int: " + num);
        } catch (NumberFormatException e) {
            System.out.println("Error: Invalid number format");
        }
    }
}

Output:

Error: Invalid number format