1) Integer.parseInt(), which takes a String and return an int primitive
2) Integer.valueOf() ,which accept a String and return an Integer object
Sample code to convert String to int and Integer
You can use both of these method in your code as shown below :public class Sample{ public static void main(String args[]){ int i = Integer.parseInt("3"); int j = Integer.valueOf("4"); System.out.println("i : " + i); // print i : 3 System.out.println("j : " + j); // print j : 4 } }
You can see that i and j holds the value of respective String. Now, let's learn some pro tips, which will help you to make full use of these two methods.
Pro Tips
1) Use Integer.parseInt() for converting String to int primitive and Integer.valueOf() for converting String to Integer object.2) Integer.valueOf() internally calls parseInt() method for parsing String to int value, as shown below
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }
3) Integer.valueOf() can return cached object because it maintain a pool of Integer object in a range -128 to 127 and always return same object, similar to String literal. You can see this in following code snippet of valueOf() method taken from JDK codebase :
public static Integer valueOf(int i) { assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)]; return new Integer(i); }
4) Both methods throws NumberFormatException if given String is not a valid number. Apart from digits 0 to 9, only + and - character are acceptable.
5) One you got the int primitive, you can also use auto-boxing to convert it to Integer, but that internally uses Integer.valueOf() method as well.
Simple tips to convert String to int primitive and Integer object in Java. Use Integer.parseInt() for converting a numeric String to int and Integer.valueOf() to convert a numeric String to Integer object in Java.
ReplyDelete