String to int in java

Here we see different ways to convert String to int in java.

Using Integer.parseInt() – 

public class StringToIntExmp1 {
	public static void main(String[] args) {
		String s1 = "231";
		int number = Integer.parseInt(s1);
		System.out.println(number);
	}
}

Output is – 231

We have static parseInt() mthod defined in Integer class, which takes String as a parameter and return int(primitives).

Using Integer.valueOf() – 

public class StringToIntExmp1 {
	public static void main(String[] args) {
		String s1 = "231";
		int number = Integer.valueOf(s1);
		System.out.println(number);
	}
}

Output is – 231


We have static valueOf() method defined in Integer class, which has three overloaded version valueOf(int i), valueOf(String s) and valueOf(String s, int regex). So what is the difference between parseInt() and valueOf() method, why java engineers have defined two methods, which is doing the same task? parseInt() return int as primitives value whereas the valueOf() return Integer Object. Again in above program, if valueOf() returns Integer why we are not getting any compilation error (we can’t assign int to Integer). JDK 5 onwards we can do it, in JDK 1.5 we have autoboxing and unboxing concept. JVM will take care to convert int to Integer and Integer to int.


What will happen if we will try to parse a String which contains character instead of int?  Let’s see –

public class StringToIntExmp1 {
	public static void main(String[] args) {
		String s1 = "somechar";

		int number = Integer.parseInt(s1);
		System.out.println(number);
	}
}

Output is –

Exception in thread “main” java.lang.NumberFormatException: For input string: “somechar”
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at StringToIntExmp1.main(StringToIntExmp1.java:5)