Convert String to int using Java




Java Tutorial for Beginners
Java Tutorial for Beginners

In Java, we can use Integer.parseInt() method to convert a String to int.

Example 1. Using Integer.parseInt()

public static int parseInt(String s, int radix) throws NumberFormatException Parses the string argument as a signed decimal integer.
The Example below can be used to convert a String “1000” to an primitive integer.

/*
 java string to int
*/

public class StringToInt {

    public static void main(String[] args) {

        String number = "1000";
        int value = Integer.parseInt(number);
        System.out.println(value);

    }
}

/*
Output:
1000

*/

Integer.parseInt() throws NumberFormatException

/*
 java string to int
*/

public class StringToInt {

    public static void main(String[] args) {

        String number = "1000abcdef";
        int value = Integer.parseInt(number);
        System.out.println(value);

    }
}

/*
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "1000abcdef"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at app.main(app.java:10)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:483)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

*/

Other examples of using Integer.parseInt()

Examples:

 parseInt("0", 10) returns 0
 parseInt("473", 10) returns 473
 parseInt("+42", 10) returns 42
 parseInt("-0", 10) returns 0
 parseInt("-FF", 16) returns -255
 parseInt("1100110", 2) returns 102
 parseInt("2147483647", 10) returns 2147483647
 parseInt("-2147483648", 10) returns -2147483648
 parseInt("2147483648", 10) throws a NumberFormatException
 parseInt("99", 8) throws a NumberFormatException
 parseInt("Kona", 10) throws a NumberFormatException
 parseInt("Kona", 27) returns 411787

Example 2. Java convert string to int Using Integer.valueOf()

Integer.valueOf() Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument.

/*
 java string to int
*/

public class StringToInt {

    public static void main(String[] args) {

        String number = "1000";
        Integer value = Integer.valueOf(number);
        System.out.println(value);

    }
}

/*
Output:
1000

*/

Sources:

 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*