Gareth D.
—How can I convert a String to an int in Java?
The two easiest ways to convert a string to an integer in Java are to use Integer.parseInt()
or Integer.valueOf()
.
Here is an example of each. Note that both could throw a NumberFormatException
if the input string contains characters that cannot be converted to an integer, so your code should handle this in a try...catch
block.
Integer.valueOf
class Main { public static void main(String[] args) { String validString = "123"; String invalidString = "123x"; Integer number; try { number = Integer.valueOf(validString); System.out.println("Converted integer: " + number); number = Integer.valueOf(invalidString); System.out.println("Converted integer: " + number); } catch (NumberFormatException e) { System.out.println("Invalid integer input"); } } }
This will output the following.
Converted integer: 123 Invalid integer input
In the above example, validString
is successfully converted as it contains only numerical characters. The invalidString
variable contains a non-numeric character and cannot be converted, so we instead see the output from the catch
block.
Integer.parseInt()
The code below has only three differences from the previous example. We use int number;
instead of Integer number
to declare our variable that will hold the result, and we changed both instances of valueOf
to parseInt
. The output and other functionality are otherwise identical.
class Main { public static void main(String[] args) { String validString = "123"; String invalidString = "123x"; int number; try { number = Integer.parseInt(validString); System.out.println("Converted integer: " + number); number = Integer.parseInt(invalidString); System.out.println("Converted integer: " + number); } catch (NumberFormatException e) { System.out.println("Invalid integer input"); } } }
Integer
and int
Modern Java versions running on modern systems are very efficient and there should be practically no performance difference between using primitive int
and declaring new Integer
objects, so you should consider convenience over performance in nearly all cases. Although initializing new Integer
objects will take up some extra memory, this will be trivial unless you are keeping vast amounts in memory simultaneously.
Instead, you might consider factors such as:
Integer
is nullable which might be useful.Integer
includes other helper methods, which you might need if you do further processing after the conversion.int
can behave more predictably and manipulating int
variables sometimes requires less code.For example, consider the following:
class Main { public static void main(String[] args) { String s1 = "1000"; String s2 = "1000"; Integer n1 = Integer.valueOf(s1); Integer n2 = Integer.valueOf(s2); System.out.println("n1 == n2: " + String.valueOf(n1 == n2)); } }
Even though both s1
and s2
represent the same number (1000), this prints out:
n1 == n2: false
This is because n1
and n2
are different objects with different memory addresses.
Confusingly, the following code—which is identical except that it uses the value “100” instead of “1000”—behaves differently:
class Main { public static void main(String[] args) { String s1 = "100"; String s2 = "100"; Integer n1 = Integer.valueOf(s1); Integer n2 = Integer.valueOf(s2); System.out.println("n1 == n2: " + String.valueOf(n1 == n2)); } }
This prints:
n1 == n2: true
This difference in behavior is because Java caches smaller integer values for efficiency, so in the second example, both values are saved as the same object.
Using parseInt()
and int
primitives can avoid issues like this, giving you n1 == n2: true
in both cases. However, using Integer
has the benefit of the helper methods it contains and the ability to deal with null values.
If you’re looking to get a deeper understanding of how Java application monitoring works, take a look at the following articles:
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.