Java Integer valueOf() method
The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns an Integer object which represents the specified String when parsed with the given radix. Syntax
- public static Integer valueOf (int i)
- public static Integer valueOf(String s) throws NumberFormatException
- public static Integer valueOf(String s, int radix) throws NumberFormatException
public class JavaIntegerValueOfExample1 { public static void main(String[] args) { // returns a Integer object which represents the specified int int val=12; System.out.println("valueOf() method returns : "+Integer.valueOf(val)); } }Output
valueOf() method returns : 12Example 2
public class JavaIntegrValueOfExample2 { public static void main(String[] args) { // returns a Integer object which represents the specified String String str="369876543234567890"; //return an exception if the string does not contain a parsable byte System.out.println("valueOf() method returns : "+Integer.valueOf(str)); } }Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "369876543234567890" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:583) at java.lang.Integer.valueOf(Integer.java:766) at com.TutorialAndExample.JavaIntegerValueOfExample2.main(JavaIntegerValueOfExample2.java:8)Example 3
public class JavaIntegerValueOfExample3 { public static void main(String[] args) { // returns a Integer object which represents the specified String when parsed with the given radix String str="36"; int radix=Character.MAX_RADIX; //return an exception if the string does not contain a parsable byte System.out.println("valueOf() method returns : "+Integer.valueOf(str,radix)); } }Output
valueOf() method returns : 114Example 4
public class JavaIntegerValueOfExample4 { public static void main(String[] args) { // returns a Integer object which represents the specified String String str="369"; int radix=98; //return an exception if the radix is greater than Character.MAX_RADIX System.out.println("valueOf() method returns : "+Integer.valueOf(str,radix)); } }Output
Exception in thread "main" java.lang.NumberFormatException: radix 98 greater than Character.MAX_RADIX at java.lang.Integer.parseInt(Integer.java:551) at java.lang.Integer.valueOf(Integer.java:740) at com.TutorialAndExample.JavaIntegerValueOfExample4.main(JavaIntegerValueOfExample4.java:9)