SyntaxRight

Getting your program syntax right!

How to convert String to Integer in Java

Use Integer.parseInt

class MyConvertor {
    public static void main(String[] args) {

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

Catch the exception if you want to handle the conversion error:

class MyConvertor {
    public static void main(String[] args) {

        String str = "abc";
        try {
            int num = Integer.parseInt(str);
            System.out.println(num);
        } catch (NumberFormatException e) {
            System.out.println("Invalid integer format"); // Output: Invalid integer format
        }
    }

Published by