Java Integer decode() method
The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers.
Syntax
public static Integer decode(String nm) throws NumberFormatException
Parameters
The parameter ‘nm’ represents the String to decode.
Throws:
The decode() method throws :
NumberFormatException- if the String does not contains a parsable integer.
Return Value
This method returns an Integer object holding the int value of string ‘nm’.
Example 1
public class JavaIntegerDecodeExample1 {
public static void main(String[] args) {
String str="12";
//decodes a String into a Integer
Integer val=Integer.decode(str);
System.out.println(val);
}
}
Output
12
Example 2
public class JavaIntegerDecodeExample2 {
public static void main(String[] args) {
//for Min.VALUE value it will give an NumberFormatException
String str="Integer.MIN_VALUE";
Integer b1=Integer.decode(str);
System.out.println(b1);
}
}
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "Integer.MIN_VALUE" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.valueOf(Integer.java:740) at java.lang.Integer.decode(Integer.java:1197) at com.TutorialAndExample.JavaIntegerDecodeExample2.main(JavaIntegerDecodeExample2.java:7)
Example 3
public class JavaIntegerDecodeExample3 {
public static void main(String[] args) {
//for Min.VALUE value it will give an NumberFormatException
String str="null";
Integer b1=Integer.decode(str);
System.out.println(b1);
}
}
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "null" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.valueOf(Integer.java:740) at java.lang.Integer.decode(Integer.java:1197) at com.TutorialAndExample.JavaIntegerDecodeExample3.main(JavaIntegerDecodeExample3.java:8)
