How to convert a string to int in Java
If you want to convert a string to int in Java, you have two simple options – parseInt()
und valueOf()
. However, both of these options only work if the string exclusively contains whole numbers and doesn’t exceed the value range of the int data type.
What is a string to int conversion in Java?
Java strings are concatenations that can contain characters, digits and special characters. In the Java programming language, digits in the form of integer values can be saved as an int. If you have a string that only contains whole numbers, you can convert it into the Java primitive int, which stands for integer. While there are 5 different ways to convert a Java int to a string, there are only 2 main ways to convert a Java string to an int. They are Integer parseInt()
and Integer.valueOf()
. Below we’ll explain how these methods work using practical examples.
Note that this conversion will only work if the number in question is between -2147483648 and 2147483647. Numbers that are larger or smaller can’t be represented using the int data type.
- 99.9% uptime
- PHP 8.3 with JIT compiler
- SSL, DDoS protection, and backups
How to use Integer.parseInt()
parseInt()
is a static method that belongs to the Integer class and returns the numerical value of the complex data type string in the form of the primitive data type int. Its syntax looks as follows:
Let’s look at an example. First we’ll initialize a string that contains the value “7312” and nothing else. Then we’ll convert that Java string to an int using parseInt()
, and finally we’ll output the result using the Java command System.out.println
. The code will look as follows:
Here’s the output:
Here’s the error message:
How to use Integer.valueOf()
Integer.valueOf()
is another method from the Integer class. It outputs the decimal interpretation of a string object and is thus also useful for converting a Java string to an int. Its syntax looks as follows:
Let’s turn to a simple example:
You’ll again get the following result:
If the string contains anything except for a whole number, we’ll get the same error message as we got above.