- Java — Convert String to long
- Long.valueOf()
- Deprecated: Long‘s Constructor
- Long.decode()
- DecimalFormat.parse()
- Apache Commons NumberUtils
- Spring NumberUtils
- Google Guava Longs.tryParse()
- How to Convert String to Long in Java
- Converting String to Long in Java using Long.parseLong()
- Converting String to Long in Java using Long.valueOf()
- Converting String to Long using new Long(String).longValue()
- Converting String to Long using DecimalFormat
- Convert string value to long in java
Java — Convert String to long
We also can use Long.parseUnsignedLong(. ) to make sure the long is > 0.
Long.valueOf()
The difference between valueOf(. ) and parseLong(. ) is valueOf(. ) will return a Long (wrapper class) instead of primitive long.
- static Long valueOf(String s): Returns a Long object holding the value of the specified String.
- static Long valueOf(String s, int radix): Returns a Long object holding the value extracted from the specified String when parsed with the radix given by the second argument.
long l1 = Long.valueOf("888"); System.out.println(l1); // 101010101 long l2 = Long.valueOf("-FF", 16); System.out.println(l2); // -255 long l3 = Long.valueOf("01010101", 2); System.out.println(l3); // 85
As you can see, implicit casting automatically unbox Long into long.
Deprecated: Long‘s Constructor
It is rarely appropriate to use this constructor. Use parseLong(String) to convert a string to a long primitive, or use valueOf(String) to convert a string to a Long object.
long l1 = new Long("123"); System.out.println(l1); // 123 long l2 = new Long("-0x8F"); // NumberFormatException System.out.println(l2);
Long.decode()
static Long decode(String nm): Decodes a String into a Long.
long l1 = Long.decode("321"); System.out.println(l1); // 321 long l2 = Long.decode("-0x88"); // hex System.out.println(l2); // -136 long l3 = Long.decode("#F3F3F3"); // hex System.out.println(l3); // 15987699 long l4 = Long.decode("066"); // octal System.out.println(l4); // 54
DecimalFormat.parse()
parse(String source) throws ParseException: Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.
import java.text.DecimalFormat; import java.text.ParseException;
DecimalFormat decimalFormat = new DecimalFormat(); try < long l = decimalFormat.parse("54321").longValue(); System.out.println(l); // 54321 >catch (ParseException e)
Since parse() method returns instance of Number, we need to call longValue() to get the long primitive value from it. The Number also has intValue() to get int primitive value, doubleValue() for double, etc.
And similar to Convert String to int, we also can use external libraries like Apache Commons NumberUtils, Spring’s NumberUtils, and Google’s Guava primitive Longs.
Apache Commons NumberUtils
- static long toLong(String str): Convert a String to a long, returning zero if the conversion fails.
- static long toLong(String str, long defaultValue): Convert a String to a long, returning a default value if the conversion fails.
- static Long createLong(String str): Convert a String to a Long; since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations.
import org.springframework.util.NumberUtils;
long l1 = NumberUtils.toLong("365"); System.out.println(l1); // 365 long l2 = NumberUtils.toLong(null); System.out.println(l2); // 0 long l3 = NumberUtils.toLong("365", 0); System.out.println(l3); // 365 long l4 = NumberUtils.toLong("xyz", -1); System.out.println(l4); // -1 long l5 = NumberUtils.toLong("", -1); System.out.println(l5); // -1 long l6 = NumberUtils.createLong("365"); System.out.println(l6); // 365 long l7 = NumberUtils.createLong("-0xFF88"); System.out.println(l7); // -65416
Spring NumberUtils
Similar like in Converting String to int, we can use Spring’s NumberUtils to parse String to number (in this case long).
import org.springframework.util.NumberUtils;
long i1 = NumberUtils.parseNumber("512", Long.class); System.out.println(i1); // 512 long i2 = NumberUtils.parseNumber("#F120", Long.class); System.out.println(i2); // 61728
Google Guava Longs.tryParse()
The conversion also can be done using Guava’s Longs.tryParse().
- static Long tryParse(String string): Parses the specified string as a signed decimal long value.
- static Long tryParse(String string, int radix): Parses the specified string as a signed long value using the specified radix.
import com.google.common.primitives.Longs;
long l1 = Longs.tryParse("5123456789012346"); System.out.println(l1); // 5123456789012346 long l2 = Longs.tryParse("-18F1", 16); System.out.println(l2); // -6385 long l3 = Longs.tryParse("111111111", 2); System.out.println(l3); // 511
Liked this Tutorial? Share it on Social media!
How to Convert String to Long in Java
In this tutorial, we will learn how to convert Java String to wrapper Long class object or primitive type long value easily.
There are some situations where we need to convert a number represented as a string into a long type in Java.
It is normally used when we want to perform mathematical operations on the string which contains a number.
For example, whenever we gain data from JTextField or JComboBox, we receive entered data as a string. If entered data is a number in string form, we need to convert the string to a long to perform mathematical operations on it.
There are mainly four different ways to convert a string to wrapper Long class or primitive type long.
- Convert using Long.parseLong()
- Convert using Long.valueOf()
- Using new Long(String).longValue()
- Using DecimalFormat
Let’s understand all four ways one by one with example programs.
Converting String to Long in Java using Long.parseLong()
To convert string to a long, we use Long.parseLong() method provided by the Long class. The parseLong() of Long class is the static method. It reads long numeric values from the command-line arguments.
So, we do not need to create an object of class to call it. We can call it simply using its class name. The general signature of parseLong() method is as below:
public static long parseLong(String s)
This method accepts a string containing the long representation to be parsed. It returns long value. The parseLong() method throws an exception named NumberFormatException if the string does not contain a parsable long value.
Let’s create a Java program to convert string to long in java using parseLong() of Java Long class.
Program code 1:
// Java program to convert a string into a primitive long type using parseLong() method. package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "99904489675"; // Call parseLong() method to convert a string to long value. long l = Long.parseLong(str); System.out.println(l); ++l; System.out.println(l); >>
Output: 99904489675 99904489676
Converting String to Long in Java using Long.valueOf()
We can also convert a string to long numeric value using valueOf() of Java long wrapper class. The valueOf() method of Long class converts a string containing a long number into Long object and returns that object.
It is a static utility method, so we do not need to create an object of class. We can invoke it using its class name.The general signature of valueOf() method is as below:
public static Long valueOf(String str)
Let’s write a Java program to convert a string into a long value using valueOf() method of Java Long wrapper class.
Program code 2:
// Java program to convert a string into a primitive long type using valueOf() method. package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "99904489675"; // Call parseLong() method to convert a string to long value. Long l = Long.valueOf(str); System.out.println(l); >>
Converting String to Long using new Long(String).longValue()
Another alternative approach is to create an instance of Long class and then call longValue() method of Long class. The longValue() method converts the long object into primitive long type value. This is called “unboxing” in Java.
Unboxing is a process by which we convert an object into its corresponding primitive data type.
Let’s create a Java program to convert String into a long object using longValue() method.
Program code 3:
// Java program to convert a string into a long using new Long(String).longValue(). package javaConversion; public class StringToLongConversion < public static void main(String[] args) < String str = "757586748"; Long l = new Long(str); long num = l.longValue(); System.out.println(num); >>
Converting String to Long using DecimalFormat
Java provides a class called DecimalFormat that allows to convert a number to its string representation. This class is present in java.text package. We can also use in other way to parse a string into its numerical representation.
Let’s create a Java program to convert a string to long numeric value using DecimalFormat class.
Program code 4:
// Java Program to demonstrate the conversion of String into long using DecimalFormat class. package javaConversion; import java.text.DecimalFormat; import java.text.ParseException; public class StringToLongConversion < public static void main(String[] args) < String str = "76347364"; // Create an object of DecimalFormat class. DecimalFormat decimalFormat = new DecimalFormat("#"); try < long num = decimalFormat.parse(str).longValue(); System.out.println(num); >catch (ParseException e) < System.out.println(str + " is not a valid numeric value."); >> >
In this tutorial, you learned how to convert a string to long numeric value in Java using the following ways easily. Hope that you will have understood the basic methods of converting a string into a long.
In the next tutorial, we will learn how to convert long numeric value to a string in Java.
Thanks for reading.
Next ⇒ Convert Long to String in Java ⇐ Prev Next ⇒
Convert string value to long in java
- A quick intro to the MACH architecture strategy While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .
- How to maintain polyglot persistence for microservices Managing microservice data may be difficult without polyglot persistence in place. Examine how the strategy works, its challenges.
- Top developer relations trends for building stronger teams Learn about enterprise trends for optimizing software engineering practices, including developer relations, API use, community .
- The basics of implementing an API testing framework With an increasing need for API testing, having an efficient test strategy is a big concern for testers. How can teams evaluate .
- The potential of ChatGPT for software testing ChatGPT can help software testers write tests and plan coverage. How can teams anticipate both AI’s future testing capabilities .
- Retail companies gain DORA metrics ROI from specialist tools DORA metrics and other measures of engineering efficiency are popping up in add-ons to existing DevOps tools. But third-party .
- How to create and manage Amazon EBS snapshots via AWS CLI EBS snapshots are an essential part of any data backup and recovery strategy in EC2-based deployments. Become familiar with how .
- Prices for cloud infrastructure soar 30% Tough macroeconomic conditions as well as high average selling prices for cloud computing and storage servers have forced .
- Deploy a low-latency app with AWS Local Zones in 5 steps Once you decide AWS Local Zones are right for your application, it’s time for deployment. Follow along in this step-by-step video.
- Multiple Adobe ColdFusion flaws exploited in the wild One of the Adobe ColdFusion flaws exploited in the wild, CVE-2023-38203, was a zero-day bug that security vendor Project .
- Ransomware case study: Recovery can be painful In ransomware attacks, backups can save the day and the data. Even so, recovery can still be expensive and painful, depending on .
- Supercloud security concerns foreshadow concept’s adoption Supercloud lets applications work together across multiple cloud environments, but organizations must pay particular attention to.
- AWS Control Tower aims to simplify multi-account management Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .
- Break down the Amazon EKS pricing model There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .
- Compare EKS vs. self-managed Kubernetes on AWS AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .