2 ways to parse String to int in Java

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 parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about Integer.valueOf() method, which implements 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 return the same value from cached pool. The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to 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.




Java Program to Parse String to Int

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 which 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 valid values in numeric String. You will get same errors even if you use Integer.valueOf() method because valueOf() method internally calls parseInt() method to parse String to integer in Java.

2 examples to parse String to Int 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 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 save memory and time.

Though, you need to be careful while comparing it because if you use  equality operator (== )then Java compare their references and return 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 == operator is working but then you will see issues when Integer object is outside of that range, in that case, == operator will not work. In short, you have created a bug which 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 brings 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 long in Java? (answer)
If you are learning Java and looking for a good companion book you can check out following titles, two of the most recommended books for Java beginners:
  • Java : How to Program by Deitel and Deitel 9th Edition (see here)
  • Core Java Volume 1 and 2, 9th Edition by Cay S. Horstmann (see here)


No comments:

Post a Comment