Java String to int example shows how to convert string to int in Java using the parseInt method of the Integer wrapper class including the NumberFormatException.
How to convert String to int in Java?
To convert a string to int, we can use the parseInt
method of the Java Integer
wrapper class.
1 |
public static int parseInt(String str) |
This method returns an int primitive value by parsing the input string value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.javacodeexamples.basic; public class StringToIntExample { public static void main(String[] args){ String strNumber = "3243"; /* * use Integer.parseInt() method to * convert string to int primitive value */ int i = Integer.parseInt(strNumber); System.out.println("String to int: " + i); } } |
Output
1 |
String to int: 3243 |
Important Note:
All the characters in the string must be a digit, except for the first character of the string which can be a “-” (minus sign) to indicate the negative numeric value.
If any of the characters in the string (except for the first character, if it is a minus sign) is a non-digit character, the NumberFormatException is thrown while converting the string to an int value.
1 2 |
String strNumber = "3.243"; int i = Integer.parseInt(strNumber); |
Output
1 2 3 4 5 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "3.243" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at com.javacodeexamples.basic.StringToIntExample.main(StringToIntExample.java:19) |
Here are some of the example string values and their possible outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//123 System.out.println( Integer.parseInt("123") ); //NumberFormatException System.out.println( Integer.parseInt("2.43") ); //-123 System.out.println( Integer.parseInt("-123") ); //NumberFormatException System.out.println( Integer.parseInt("abc123") ); //remove leading zeros - 423 System.out.println( Integer.parseInt("000423") ); //NumberFormatException in older version of Java, 423 in newer System.out.println( Integer.parseInt("+423") ); /* * even empty string is not allowed, * NumberFormatException is thrown for input String: "" */ System.out.println( Integer.parseInt("") ); |
Please note that the “+” (plus sign) is allowed as the first character of the string only in the newer versions of Java. In older versions, if the string has a plus sign as the first character, the parseInt
method throws a NumberFormatException exception.
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.