How to convert a String to int in Java

We can convert a String to a primitive int using the Integer.parseInt method or to a wrapped Integer class using the Integer.valueOf. When both methods receive an invalid number as argument, a java.lang.NumberFormatException will be thrown.

Convert String to int using Integer.parseInt

The Integer.parseInt method is used to convert a String to primitive int.

String number = "1234";
int convertedNumber = Integer.parseInt(number);
System.out.println("Convert String to int: " + convertedNumber);

String negativeNumber = "-1234";
int convertedNegativeNumber = Integer.parseInt(negativeNumber);
System.out.println("Convert negative String to int: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to int: 1234
Convert negative String to int: -1234

Convert String to Integer using Integer.valueOf

The Integer.valueOf method is used to convert a String to a wrappedInteger.

String number = "1234";
Integer convertedNumber = Integer.valueOf(number);
System.out.println("Convert String to Integer: " + convertedNumber);

String negativeNumber = "-1234";
Integer convertedNegativeNumber = Integer.valueOf(negativeNumber);
System.out.println("Convert negative String to Integer: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to Integer: 1234
Convert negative String to Integer: -1234

throws java.lang.NumberFormatException

If the String passed in is not a valid Integer, an java.lang.NumberFormatException is thrown. In this example "-abc" is not a valid number for type Integer.

String invalidNumber = "-abc";
int invalidConvertedNumber = Integer.parseInt(invalidNumber);

The java.lang.NumberFormatException thrown.

Exception in thread "main" java.lang.NumberFormatException: For input string: "-abc"
	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 com.memorynotfound.ParseIntExample.main(ParseIntExample.java:15)

References

Download

Download it ! – convert-string-to-int-java

You may also like...