Sunday, September 17, 2023

2 ways to parse String to int in Java - Example Tutorial

Java provides Integer.parseInt() method to parse a String to an int value, but that's not the only way to convert a numeric String to int in Java. There is, in fact, a better way, which takes advantage of the parsing logic of the parseInt() method as well as caching offered by the Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about the Integer.valueOf() method, which implements the Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127

So every time you pass a numeric String which is in the range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but returns the same value from the cached pool. 

The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like the parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to an int value in Java.


2 Examples to Parse String to int in Java

Here is our Java program to convert String to int in Java. This example shows how to use both Integer.parseInt() and Integer.valueOf() method to parse a numeric String to an int primitive in Java. 

In this program, we ask the user to enter a number and then we read user input from the console using Scanner class as String. Later we convert that String using both Integer.parseInt() and Integer.valueOf() method to show that both methods work and you can use either of them.

2 examples to parse String to Int in Java



Java Program to Parse String to Int

Here is our complete Java program to parse a given String to an int value in Java. You can run this program in your favorite IDEs like Visual Studio Code, Eclipse, or IntelliJ IDEA
import java.util.Scanner;

/**
 * 2 ways to convert String to int in Java.
 * User enters number, we read it as String and convert 
 * it to int using parseInt() method.
 * 
 * @author WINDOWS 8
 *
 */
public class StringToInt {

    public static void main(String args[]) {

       System.out.println("Please enter an integer number");
       
       Scanner scnr = new Scanner(System.in);
       String input = scnr.nextLine();
       
       int i = Integer.parseInt(input);
       
       System.out.println("String converted to int : " + i);
       
       System.out.println("Please enter another integer number");
       
       String str = scnr.nextLine();
       
       int j = Integer.valueOf(str); // can return cached value
       
       System.out.println("String to int using valueOf() : " + j);
        
    }

    
}

Output :
Please enter an integer number
100
String converted to int : 100
Please enter another integer number
300
String to int using valueOf() : 300

You can see that both Integer.valueOf() and Integer.parseInt() method is able to parse a numeric String. You can even pass a numeric String with Plus and Minus sign, both methods are capable of parsing them successfully as shown below :
Please enter an integer number
+201
String converted to int : 201
Please enter another integer number
-203
String to int using valueOf() : -203

but if you pass a String that contains anything other than +, - and digits, you will get java.lang.NumberFormatException as shown below :
Please enter an integer number
++201
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "++201"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

You can see even double sign is also not allowed, let's try an alphanumeric String :
Please enter an integer number
2012a44
Exception in thread "main" java.lang.NumberFormatException: 
For input string: "2012a44"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at dto.ReverseIntegerTest.main(ReverseIntegerTest.java:22)

You can see that Integer.parseInt() doesn't like anything other than valid values in numeric String. You will get the same errors even if you use Integer.valueOf() method because valueOf() method internally calls parseInt() method to parse String to integer in Java.


That's all about how to parse String to int in Java. Even though parseInt() is the standard way to parse String to int, you should try to use Integer.valueOf() method. It implements a Flyweight design pattern and maintains a pool of frequently used int values e.g. int primitives from -128 to 127 and that's how it saves memory and time.

Though, you need to be careful while comparing it because if you use equality operator (== )then Java compares their references and returns true only if both variables are pointing to the same object e.g. one of the Integer objects returned from a cached pool.

So you think that the == operator is working but then you will see issues when the Integer object is outside of that range, in that case, the == operator will not work. In short, you have created a bug that is hard to find. See this story to learn more about this bug.

BTW, if you are learning Java and want to master fundamentals, I suggest you take a look at Head First Java 2nd Edition, they explain the concept in the easiest way possible but also bring out important details.


If you are new to Java and wants to learn about how to convert one type to another, check out my following data type conversion tutorials :
  • How to convert String to Double in Java? (example)
  • How to convert ByteBuffer to String in Java? (program)
  • How to convert double to Long in Java? (program)
  • How to convert float to String in Java? (example)
  • How to convert byte array to String in Java? (program)
  • How to convert Enum to String in Java? (example)
  • How to convert String to int in Java? (example)
  • How to convert Decimal to Binary in Java? (example)
  • How to convert String to Date in a thread-safe manner? (example)
  • How to parse String to a long value in Java? (answer)
Thanks for reading this article so far. If you find these String to int parsing examples in Java useful then please share this example with your friends and colleagues. 

Over to you, what is your favorite way to convert String to int in Java? parseInt() or valueOf() and which one is better from performance point of view? and why?

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.