Java Integer parseInt() method
The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified by the second argument. The third parameter parses the CharSequence argument as a signed int in the specified radix, beginning at the specified beginIndex and extending to endIndex -1. Syntax
- public static int parseInt(String s) throws NumberFormatException
- public static int parseInt(String s, int radix) throws NumberFormatException
- public static int parseInt(CharSequence s, int beginIndex, int endIndex, int radix) throws NumberFormatException
public class JavaIntegerParseIntExample1 { public static void main(String[] args) { String s="123"; //parses the CharSequence argument as a signed decimal integer int val=Integer.parseInt(s); System.out.println(val); } }Output
123Example 2
public class JavaIntegerParseIntExample2 { public static void main(String[] args) { String s="123"; int radix=9; //parses the string argument as a signed integer in the radix specified by the second argument int val=Integer.parseInt(s,radix); System.out.println(val); } }Output
102Example 3
public class JavaIntegerParseIntExample3 { public static void main(String[] args) { String s="123"; //radix should be smaller than Character.MAX_RADIX i.e. 36 else it will give you an error int radix=37; //parses the string argument as a signed integer in the radix specified by the second argument int val=Integer.parseInt(s,radix); System.out.println(val); } }Output
Exception in thread "main" java.lang.NumberFormatException: radix 37 greater than Character.MAX_RADIX at java.lang.Integer.parseInt(Integer.java:551) at com.TutorialAndExample.JavaIntegerParseIntExample3.main(JavaIntegerParseIntExample3.java:9)Example 4
public class JavaIntegerParseIntExample4 { public static void main(String[] args) { //give NumberFormatException if the String does not contain a parsable int String s=null; //radix should be smaller than Character.MAX_RADIX i.e. 36 else it will give you an error int radix=37; /*It parses the CharSequence argument as a signed as a signed int in the specified radix, beginning at the specified beginIndex and extending to endIndex -1.*/ int val=Integer.parseInt(s,radix); System.out.println(val); } }Output
Exception in thread "main" java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:542) at com.TutorialAndExample.JavaIntegerParseIntExample4.main(JavaIntegerParseIntExample4.java:10)