Sunday, September 24, 2023

4 Ways to Convert String to long in Java? Example Tutorial

How to convert a string to long in Java is one of those frequently asked questions by a beginner who has started learning Java programming language and is not aware of how to convert from one data type to another. Converting String to long is similar to converting String to Integer in Java, in-fact if you know how to convert String to Integer then you can convert String to Long by following the same procedure. Though you need to remember few things while dealing with long and String first of all long is the primitive type which is wrapped by the Long wrapper class and String is an Object in Java backed by character array.

Before Java 5 you need to take an extra step to convert a Long object into a long primitive but after the introduction of autoboxing and unboxing in Java 5, Java language will perform that conversion for you. 

This article is in continuation of our previous conversion tutorial like how to convert String to Double in Java or how to convert String to Enum in Java

In this Java tutorial, we will learn 3 different ways to convert String to long by code examples and we will also analyze the pros and cons of each approach.




How to convert String to long in Java? 

Here are 3 different ways to convert a String to a long primitive value in Java:
  1. Using Long.valueOf() method
  2. Using Long.parseLong() method
  3. Using java.lang.Long constructor
  4. Using Long decode() method



1. String to long in Java - Long.valueOf Example

3 example to convert String to long in Java with exampleLong.valueOf() is static factory method from java.lang.Long class which accepts a String argument and returns an equivalent long primitive value. Long.valueOf() will throw NumberFormatException if String is not convertible into long due to any reason like String contains a non-numeric value, the numeric value of String is beyond MAX and MIN value of Long, etc. 

Though negative sign can be included to denote negative long value as the first character. The main advantage of valueOf() is that it's a static factory method and can cache frequently used long values, since long is an immutable object it's safe to reuse cached long values.

The valueOf() is also an overloaded method that accepts radix as the second argument to convert hexadecimal or octal String to long. Here is an example of converting String to long value using the valueOf method in Java:

long decimalNumber = Long.valueOf("55555");
long octalNumber = Long.valueOf("55555", 8);
long hexNumber = Long.valueOf("5555", 16);

As per caching JDK's Long.valueOf() method caches values up to -128 to 127 and returns the same Long object which will return true if compared with equality operator "==". you can also look code of valueOf() method on java.lang.Long class to verify it.



2. String to long in Java - Long.parseLong Example

Long.parseLong() is another static method from java.lang.Long class which converts String into a long value. parseLong() also throws java.lang.NumberFormatException if a provided String value is not convertible into long and also provides an additional overloaded method which accepts radix to convert octal and hexadecimal long values in String format

Most of the String to long conversion uses parseLong for the conversion part, in fact, Long.valueOf() also calls the parseLong method to convert long to String.

parseLong() also accepts negative sign as the first character in string input.  

Though "l" and "L" values are not permitted inside String input and throw NumberFormatException.

long negativeLong = Long.parseLong("-1024"); //represent negative long value
long incorrectLong = Long.parseLong("-1024L"); // "L" is not permitted result in NumberFormatException



3. Long.decode() and Long Constructor

Other two methods using a java.lang.Long constructor which accepts String and Long.decode() also works in a similar fashion. 

They also throw NumberFormatException if String is not convertible into long. Long.decode() is good in terms it accepts "#" as an indication of hexadecimal long values. 

It also accept "0" for octal long numbers, "0x" and "0X" for hexadecimal long numbers. Here is an example of using Long.decode() method to convert a hexadecimal long String value into a long primitive number:

long number = Long.decode("#FFFF");  //65535 in decimal

see code example section for more examples of decode() method of the Long class.

4. Code Example - String to long conversion in Java

Here is a complete code example of all four ways to convert String to long in Java discussed in this Java tutorial.

/**
 * Java program to convert String to long in Java. In this program, we will see 4 examples
 * to convert String to long primitive in Java.
 * @author Javin Paul
 */

public class StringToLong {

    public static void main(String args[]) {
       String strLong = "2323232";
     
       //Convert String to long using Long.valueOf(),better because
       //it can cache frequently used long values
       long number = Long.valueOf(strLong);
       System.out.println("String to long conversion using valueOf :" + number);
     
       //Convert String to long in Java using java.lang.Long object
       strLong ="4444444444444444444";
       Long numberObject = new Long(strLong);
       number = numberObject; //auto boxing will take care of long to Long conversion
       System.out.println("String to long conversion example using Long object: " + number);
     
       //Convert String to long with Long.parseLong method in Java
       strLong="999999999999999999";
       Long parsedLong = Long.parseLong(strLong) ;
       number = parsedLong; //auto-boxing will convert Long object to primitive long
       System.out.println("String to long conversion using parseLong() method: " + number);
     
       //Convert String to long using Long.decode() method in Java
       strLong ="-1023454";
       number = Long.decode(strLong);
       System.out.println("String to long conversion using decode() method: " + number);
     
       //String to long in hexadecimal format
       strLong ="0xFFFF";
       number = Long.decode(strLong);
       System.out.println("String to long example in hex format decode() method: " + number);
   
       //String to long in octal format
       strLong ="0777";
       number = Long.decode(strLong);
       System.out.println("String to long example in octal format decode() method: " + number);
    }
}

Output:
String to long conversion using valueOf :2323232
String to long conversion example using Long object: 4444444444444444444
String to long conversion using parseLong() method: 999999999999999999
String to long conversion using decode() method: -1023454
String to long example in hex format decode() method: 65535
String to long example in octal format decode() method: 511


That’s all on How to convert String to long in Java. We have seen four ways to change String values to long e.g. Long.valueOf(), Long.parseLong() and Long.decode() method along with classic constructor approach for converting String to long in Java. 

I personally prefer Long.valueOf() most of the time and Long.parseLong() in the rest of time to convert String to long.


Other Java programming tutorials for beginners from Javarevisited Blog

And, lastly one question for you? Which one is your favorite way to convert String to long in Java?  Long.parseLong() or valueOf()? Can you also use these way to convert String to Long object in Java? If not why not?

2 comments :

Anonymous said...

Good that you have not used plus sign in any of your example because it's only supported from Java 7 e.g. Long.valueOf("+1000000000000") will not work in Java 6 but work in Java 7.

Anonymous said...

Here is couple of more ways to convert String to long value in Java

Post a Comment