String to int in Java: 4 Ways Plus a Secret Lifehack

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction: Why does this question torment even experienced Java developers?

If you've ever Googled "How do I convert a String to an int in Java?", you are not alone. This is one of the most popular questions on Stack Overflow with millions of views. It seems simple, right? Take a string, convert it to a number — and you're done. But in practice, converting String to int in Java hides pitfalls: from unexpected exceptions to choosing between performance and code readability.

In this article, we will break down all the popular ways to convert a string to a number in Java, comparing them by speed, safety, and convenience. You will learn how to avoid the classic NumberFormatException error and get ready-made solutions for real projects. Let's go!



Method #1: The Classic — Integer.parseInt()

The most common and fastest way to convert String to int in Java is using the static method Integer.parseInt(). It takes a string and returns the primitive type int.



public class ParseIntExample {    public static void main(String[] args) {        String number = "42";        int result = Integer.parseInt(number);        System.out.println(result); // Output: 42    }}


Pros of Integer.parseInt():

  • Maximum performance — does not create unnecessary objects.
  • Simplicity — one line of code without extra wrappers.
  • Radix support — you can specify the base: Integer.parseInt("ff", 16) returns 255.


Cons and pitfalls:

  • If the string contains non-numeric characters (spaces, letters), a NumberFormatException is thrown.
  • Does not handle null — will cause a NullPointerException.


// Error example:String badInput = "42abc";int value = Integer.parseInt(badInput); // NumberFormatException!


Method #2: The Safe Integer.valueOf()

The second popular way to convert a string to a number in Java is Integer.valueOf(). It looks similar to parseInt() but returns an Integer object instead of a primitive.



public class ValueOfExample {    public static void main(String[] args) {        String number = "123";        Integer result = Integer.valueOf(number);        System.out.println(result); // Output: 123    }}


When to use valueOf()?

  • If you need an Integer object for collections (e.g., List<Integer>).
  • If you are working with Optional or Stream API (see below).
  • Thanks to caching (for numbers from -128 to 127), valueOf() can even be faster than parseInt() + autoboxing.


Important nuance:

If you need the primitive int, it's better to use parseInt() — it is about 10-15% faster because it does not create a wrapper object. However, in 99% of applications, this difference is negligible.



Method #3: Java 8+ and Optional — Elegant Error Handling

A modern approach to converting String to int in Java is using Optional. It allows you to avoid try-catch blocks and make the code cleaner.



import java.util.Optional;

public class OptionalParseExample { public static Optional<Integer> safeParseInt(String str) { try { return Optional.of(Integer.parseInt(str)); } catch (NumberFormatException e) { return Optional.empty(); } }

public static void main(String[] args) { // Successful parsing safeParseInt("100").ifPresent(System.out::println); // 100

Blogs

Book Recommendations