How to parse String to long in Java? Example

You can parse a String literal containing valid long value into a long primitive type using parseLong() and valueOf() method of java.lang.Long class of JDK. Though there is a couple of difference between valueOf() and parseLong() method e.g. valueOf() method return a Long object while parseLong() method return a Long object, but given we have autoboxing in Java, both method can use for parsing String to create long values. In the last article, you have learned how to convert a Long value to a String in Java, and in this tutorial, you will learn the opposite, i.e. how to parse a String to a long value in Java

As I said, there are a couple of ways to do it, but the most important method is parseLong(). This method is responsible for parsing input String and creating primitive long values corresponding to input String. 

It does input validation and throws NumberFormatException if you pass String which is not valid long value e.g. alphanumeric String, String containing characters other than +, - and numbers, long values which are out of range, lonely + or - character, etc.

You can also use the constructor of the Long class which accepts a String and returns a Long object, but internally it also uses the parseLong() method.

BTW, if you have just started learning Java or looking forward to learning Java from scratch, I suggest you take a look at Cay S. Horstmann's Core Java Volume 1, 9th Edition book. You will learn most of the Java fundamentals in a quick time.




Three ways to convert String to long in Java

There are three main ways to convert a numeric String to Long in Java, though internally all of them use the parseLong() method to parse numeric String to Long value.
  • By using Long.parseLong() method
  • By using Long.valueOf() method
  • By using new Long(String value) constructor

The minordifference between parseLong() and valueOf() method is that former return a primitive long value while later return a Long object. Since Long.valueOf() is also used in autoboxing to convert primitive long to Long object, it also maintains a cache of a Long object from -128 to 127. 

So it returns the same Long object for every call in this range. This is OK because Long is Immutable in Java, but it can create subtle bugs if you compare auto-boxed values using the == operator in Java, as seen in this article.

You can also check Cay S. Horstmann's Core Java Volume 1 - Fundamentals to learn more about how to convert one data type to another in Java.

How to convert Long to String in Java with example



String to Long Java Example

Here is our sample Java program to parse String to long values. In this example, I have used different long values to demonstrate how the parseLong() method works e.g. a simple long value, a long value with a plus sign, a long value with a minus sign, and a huge long value which is out of range. 

Our program will throw NumberFormatException for that value and that's why it is commented in source code. You can un-comment and run this program to see how it behaves.

/**
 * Java Program to convert String to long
 * 
 * @author java67
 */

public class StringRotateDemo {

    public static void main(String args[]) {

        // Some long values as String literal for testing 
        String simpleLong = "2223349494943933";
        String longWithPlusSign = "+45523349494943933";
        String longWithMinusSign = "-745523349494943933";
        String outOfBoundLong 
           = "787888888888888888888888888888888888888883333333333333333333";
        
        
        // converting String to long using Long.parseLong() method
        long value1 = Long.parseLong(simpleLong);
        long value2 = Long.parseLong(longWithPlusSign);
        long value3 = Long.parseLong(longWithMinusSign);
        
        // below will throw NumberFormatException because long value
        // is out of range
        //long value4 = Long.parseLong(outOfBoundLong);
        
        System.out.printf("String %s converted to long value %d %n",
                simpleLong, value1);
        System.out.printf("String %s converted to long value %d %n",
                longWithPlusSign, value2);
        System.out.printf("String %s converted to long value %d %n",
                longWithMinusSign, value3);
        
        
        // System.out.printf("String %s converted to long value %d %n",
        // outOfBoundLong, value4);
        
        
        // second method to convert a String literal to long value is
        // by using valueOf() method of Long class
        
        long value4 = Long.valueOf(simpleLong);
        long value5 = Long.valueOf(longWithPlusSign);
        long value6 = Long.valueOf(longWithMinusSign);
        
        // long value7 = Long.valueOf(outOfBoundLong); NumberFormatException
        
        System.out.println("String : " + simpleLong + " long : " + value4);
        System.out.println("String : " + longWithPlusSign + " long : " 
                    + value5);
        System.out.println("String : " + longWithMinusSign + " long : "
                    + value6);
       // System.out.println("String : " + outOfBoundLong + " long : " 
                   + value7);
        
    }

}

Output
String 2223349494943933 converted to long value 2223349494943933 
String +45523349494943933 converted to long value 45523349494943933 
String -745523349494943933 converted to long value -745523349494943933 
String : 2223349494943933 long : 2223349494943933
String : +45523349494943933 long : 45523349494943933
String : -745523349494943933 long : -745523349494943933

From the output, you can see that converted long values are the same as the original String, which means our program is working properly.



Error while Parsing String to Long 

You will get the following error  when you try to parse an out of range long value as String literal using Long.parseLong() method :
Exception in thread "main" java.lang.NumberFormatException: For input string: 
"787888888888888888888888888888888888888883333333333333333333"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at dto.ParseLongDemo.main(ParseLongDemo.java:24)

same error will also come if you use Long.valueOf() to do the parsing, this also proves that valueOf() internally calls to parseLong() method for parsing String  :
Exception in thread "main" java.lang.NumberFormatException: For input string: 
"787888888888888888888888888888888888888883333333333333333333"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Long.parseLong(Unknown Source)
    at java.lang.Long.valueOf(Unknown Source)
    at dto.ParseLongDemo.main(ParseLongDemo.java:45)



Important things to Remember

1. Long.valueOf() method actually calls Long.valueOf(long, radix) method which is used to parse String to long in any radix e.g. binary, octal, decimal and hexadecimal. Since more often you would like to parse decimal String to long, JDK has provided a valueOf() method just for that purpose. Here is the code snippet from java.lang.Long class :

public static Long valueOf(String s) throws NumberFormatException {
        return Long.valueOf(parseLong(s, 10));
}

You can see that even this method is using parseLong() method to actually convert String to long in Java, the valueOf() method is just used here to automatically convert a primitive long to a Long object. 

Like the valueOf() method of other wrapper classes e.g. Integer, Long also caches frequently used primitive value and return the same instance of a Long object. 

Since Long is Immutable in Java, it's safe to share one instance with multiple users. This is also a good example of a Flyweight design pattern. Here is the code snippet from JDK :

public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
}

Since this method is also used in auto-boxing, you should never compare auto-boxed numeric values using == operator in Java.

2) Constructor of Long class which takes a String object and return a Long object also uses parseLong() method for parsing, as shown below :

public Long(String s) throws NumberFormatException {
        this.value = parseLong(s, 10);
}

3) The real method, parseLong() which does all the work of parsing throws NumberFormatException for invalid inputs e.g. null values, empty values, lonely plus or minus sign, alphanumeric String, and String with out of range long values.


That's all about how to convert String to long in Java. You should use Long.valueOf() method to parse String, if you need a Long object and use parseLong() method if you want to convert String to a primitive long value. Long.valueOf() method also provides caching in range of -128 to 127. 

By the way, since we have auto-boxing in Java, which also used Long.valueOf() method,  It's always better to use parseLong() method because it's readable, reveals the real intention, handles invalid input, and specifically designed to parse String literal containing long values.

2 comments:

  1. Plus sign only works from Java version 7 - not version 6: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=5017980

    ReplyDelete
    Replies
    1. @Andres, that's true. thanks for pointing out.

      P.S. I had used Java 7 to run this program in Eclipse.

      Delete

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