In this post, we feature a comprehensive article on how to convert in Java a String to Int. We will also see examples of the parseInt and the valueOf Java methods.
Integer conversion is a frequently used procedure because
Integer are very common data types.
In this example, we are going to show two different ways of converting
Integer in Java, by using
You can also check this tutorial in the following video:
1. Syntax of parseInt() in Java
There are two different expressions for the parseInt() Java method:
The parameters are:
s: is the string, that includes the integer representation we want to parse.
radix: is optional and it represents the base of the used numbering system while parsing
Both expressions return the integer value represented by the string argument. If
radix parameter is used, the returned value is expressed by the specified radix. Otherwise the default radix is set to 10, for decimal system.
2. Syntax of valueOf() in Java
valueOf() method, which is utilized for string to int conversion too, can be expressed in two ways:
The parameters of
valueOf() method are:
s: represents the parsing string.
radix: is the radix that is used in the parsing string. This parameter is optional.
The returned value of
valueOf() method is an
Integer object that represents the string argument. If the
radix argument is used, the representation will be expressed by the specific radix. Otherwise, the value is a signed decimal integer.
3. Example of String to Integer Java conversion
Create a java class with the name
StringToIntTest.java and paste the following code.
In the code above, we use both ways in order to convert a string to int and we take some different conditions. Notice that
testString2 string contains two leading zeros. As you can see in the output below, both methods will ignore these zeros at the beginning and will display the integer. Also notice that we use
NumberFormatException if the string cannot be parsed as an integer.
You can see the output of the execution below:
With parseInt method, int1 = 123456789 and int2 = 123 NumberFormatException in parseInt, For input string: "0.0123" With valueOf method, int1 = 123456789 and int2 = 123 NumberFormatException in valueOf, For input string: "0.0123"
As you can see it throws a
NumberFormatException for the
errorString, as it couldn’t be parsed to integer. Also, the leading zeros are ignored, as we said before.
4. Download the source code
This was an example of string to integer Java conversion.
Download the source code of this example: String to Int Java Example
Last updated on Dec. 13th, 2019