Java – String to int conversion in 3 ways

In this article, we will discuss various ways to convert String to Integer in Java

Q) What is the need of converting String to primitive int or wrapper Integer-type ?

  • Generally, whenever we receive any data from web application then it is passed in the form of String only
  • To perform any mathematical operations on numbers which are received as String, we need to convert into respective data-type for further calculation/operation
  • This article explains about String to primitive int or Integer-type conversion only, but we can do conversion for other data-types like long, double, float, etc
  • Note: Likewise, sometimes Integer to String conversion is also required

1. Various ways to convert String to int (or Integer)

  1. Using Interger.parseInt(“strValue”); method –> returns primitive int value
  2. Using Integer.valueOf(“strValue”); method    –> returns Integer wrapper-type
  3. Create Integer object and then invoke intValue() method {i.e.; new Integer(“strValue”).intValue();}

Read String class in detail with example

Let us move forward and discuss all possible ways to convert String to Integer in Java

1.1 Using Interger.parseInt(“strValue”); method

  • This method can be used to convert String which constitutes of only numbers (or digits) into primitive int data-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.1 example

Method signature:

public static int parseInt(String s) throws NumberFormatException;

ConvertStringIntoIntUsingParseIntMethod.java

package in.bench.resources.string.to.integer.conversion;

public class ConvertStringIntoIntUsingParseIntMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "12345";

		// 1. converting String to int
		int iValue1 = Integer.parseInt(str1);
		System.out.println("1. Converted int value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-12345";

		// 2. converting String to int
		int iValue2 = Integer.parseInt(str2);
		System.out.println("\n2. Converted int value is : "
				+ iValue2);
	}
}

Output:

1. Converted int value is : 12345

2. Converted int value is : -12345

1.2 Using Integer.valueOf(“strValue”); method

  • This method can be used to convert String which constitutes of only numbers (or digits) into Integer wrapper-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.2 example

Method signature:

public static Integer valueOf(String s) throws NumberFormatException;

ConvertStringIntoIntUsingValueOfMethod.java

package in.bench.resources.string.to.integer.conversion;

public class ConvertStringIntoIntUsingValueOfMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "98765";

		// 1. converting String to Integer
		Integer iValue1 = Integer.valueOf(str1);
		System.out.println("1. Converted Integer value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-98765";

		// 2. converting String to Integer
		Integer iValue2 = Integer.valueOf(str2);
		System.out.println("\n2. Converted Integer value is : "
				+ iValue2);
	}
}

Output:

1. Converted Integer value is : 98765

2. Converted Integer value is : -98765

1.3 Create Integer object and then invoke intValue() method

  • Here, we will create new Integer object with String as constructor-argument
  • After creating new Integer object by passing string value, then invoke intValue() method for converting String to primitive int data-type
  • Passed string to constructor argument should constitutes of only numbers (or digits)
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.3 example

Method signature:

public Integer(String s) throws NumberFormatException;

public int intValue();

ConvertStringIntoIntUsingIntValueMethod.java

package in.bench.resources.string.to.integer.conversion;

public class ConvertStringIntoIntUsingIntValueMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "54545";

		// 1. converting String to int
		// by creating new Integer Object
		Integer integer1 = new Integer(str1);
		int iValue1 = integer1.intValue();
		System.out.println("1. Converted int value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-54545";

		// 2. converting String to int
		// by creating new Integer Object
		Integer integer2 = new Integer(str2);
		int iValue2 = integer2.intValue();
		System.out.println("\n2. Converted int value is : "
				+ iValue2);
	}
}

Output:

1. Converted int value is : 54545

2. Converted int value is : -54545

Exception scenario:

  • handle exception properly for all 3 ways
  • otherwise NumberFormatException will be thrown for incorrect string values (or not correctly formatted string)
  • and terminates program abruptly
  • we will see 3 different examples for all cases with E.1, E.2 and E.3

2. Exception scenarios:

  • In all above 3 cases, whenever string isn’t properly formatted to convert String to Integer, then NumberFormatException will be thrown
  • We will see, what happens if string isn’t correctly formatted for all 3 ways of conversion

2.1 Handle NumberFormatException while converting String to int using Integer.parseInt() method

ParseIntMethodThrowsNFE.java

package in.bench.resources.string.to.integer.conversion;

public class ParseIntMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "123ben";

		// 1. converting String to int
		int iValue1 = Integer.parseInt(str1);
		System.out.println("1. Converted int value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-123ben";

		// 2. converting String to int
		int iValue2 = Integer.parseInt(str2);
		System.out.println("\n2. Converted int value is : "
				+ iValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "123ben"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at in.bench.resources.string.to.integer.conversion
.ParseIntMethodThrowsNFE.main(ParseIntMethodThrowsNFE.java:11)

2.2 Handle NumberFormatException while converting String to int using Integer.valueOf() method

IntegerValueOfMethodThrowsNFE.java

package in.bench.resources.string.to.integer.conversion;

public class IntegerValueOfMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "987ben";

		// 1. converting String to Integer
		Integer iValue1 = Integer.valueOf(str1);
		System.out.println("1. Converted Integer value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-987ben";

		// 2. converting String to Integer
		Integer iValue2 = Integer.valueOf(str2);
		System.out.println("\n2. Converted Integer value is : "
				+ iValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "987ben"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.valueOf(Integer.java:766)
	at in.bench.resources.string.to.integer.conversion
.IntegerValueOfMethodThrowsNFE
.main(IntegerValueOfMethodThrowsNFE.java:11)

2.3 Handle NumberFormatException while converting String to int using intValue() method

IntValueMethodThrowsNFE.java

package in.bench.resources.string.to.integer.conversion;

public class IntValueMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "545ben";

		// 1. converting String to int
		// by creating new Integer Object
		Integer integer1 = new Integer(str1);
		int iValue1 = integer1.intValue();
		System.out.println("1. Converted int value is : "
				+ iValue1);

		// String with only digits and a minus sign (-)
		String str2 = "-545ben";

		// 2. converting String to int
		// by creating new Integer Object
		Integer integer2 = new Integer(str2);
		int iValue2 = integer2.intValue();
		System.out.println("\n2. Converted int value is : "
				+ iValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException:
	For input string: "545ben"
	at java.lang.NumberFormatException.forInputString(
			NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.<init>(Integer.java:867)
	at in.bench.resources.string.to.integer.conversion
.IntValueMethodThrowsNFE.main(IntValueMethodThrowsNFE.java:11)

Q) What if we want to convert primitive int data-type to Integer wrapper-type or vice-versa?

  • Auto-boxing feature available from Java 1.5 version
  • So, converting primitive data-type to wrapper-type can easily be done, by directly assigning values
  • Let’s see one example based on this auto-boxing feature

3. Auto-boxing and un-boxing feature from Java 1.5 version:

  • parseInt() method returns primitive int type but it can be easily used as Integer wrapper-type
  • as auto-boxing feature helps to convert primitive type to wrapper-types
  • similarly, Integer.valueOf() method returns Integer wrapper-type but it can also be used as primitive int data-type
  • let’s see one example on this auto-boxing feature at the very end

AutoBoxingFeatureForConversion.java

package in.bench.resources.string.to.integer.conversion;

public class AutoBoxingFeatureForConversion {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "12345";

		// string to int conversion
		int iValue1 = Integer.parseInt(str1);

		// 1. Auto-Boxing - converting int to Integer
		Integer iAutoBoxing = iValue1;
		System.out.println("1. Auto-Boxing : " + iAutoBoxing);

		// String with only digits and a minus sign (-)
		String str2 = "-98765";

		// string to Integer conversion
		Integer iValue2 = Integer.valueOf(str2);

		// 1. Un-Boxing - converting Integer to int
		int iUnBoxing = iValue2;
		System.out.println("\n2. Un-Boxing   : " + iUnBoxing);
	}
}

Output:

1. Auto-Boxing : 12345

2. Un-Boxing   : -98765

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Integer to String conversion in 6 ways
Java - StringBuilder substring() method