Converting String to long in Java
Introduction
In Java, numeric data often arrives as String objects—especially when reading user input, processing files, or handling network messages. To perform arithmetic, store the value in a numeric type, or use it with other Java libraries, you need to convert that string into a primitive long. The most common way to do this is by using the built‑in Long.parseLong(String) method, but there are also alternative approaches such as Long.That's why valueOf(String) and the older Integer. This leads to parseLong‑style utilities. This article explains the step‑by‑step process, highlights best practices, and addresses typical pitfalls so you can convert strings to long values confidently and safely.
It's where a lot of people lose the thread Most people skip this — try not to..
Understanding the long primitive type
The long primitive in Java is a 64‑bit signed integer that can hold values from ‑9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Practically speaking, because of its large range, it is ideal for timestamps, counters, or any situation where an int (32‑bit) would overflow. When you convert a string to a long, you must check that the numeric representation fits within this range; otherwise, a NumberFormatException will be thrown Turns out it matters..
This is the bit that actually matters in practice Simple, but easy to overlook..
Basic conversion using Long.parseLong
The method signature
public static long parseLong(String s) throws NumberFormatException
- Parameter –
s: the string to be parsed. It may contain an optional sign (+or-) followed by decimal digits. - Return value – the numeric value represented by the string as a long.
- Exception –
NumberFormatExceptionif the string does not have a valid long representation or if the value is out of the long range.
Simple example
String text = "42";
long number = Long.parseLong(text);
System.out.println(number); // prints 42
In this case, the string "42" is directly turned into the long value 42.
Handling sign and whitespace
parseLong automatically ignores leading and trailing whitespace, and it respects an optional sign character.
String positive = " +123 ";
String negative = "-67890";
long pos = Long.parseLong(positive); // 123
long neg = Long.parseLong(negative); // -67890
Using the method in a method body
When you need to convert a string that may be invalid, wrap the call in a try‑catch block:
String input = "12abc";
try {
long value = Long.parseLong(input);
System.out.println("Converted value: " + value);
} catch (NumberFormatException e) {
System.err.println("Invalid number: " + input);
}
Alternative: Long.valueOf
Long.In practice, valueOf(String) returns a Long object rather than a primitive long. This can be useful when you need a wrapper type for collections or when you want to benefit from Java’s caching of common long values (‑128 to 127).
String s = "999";
Long wrapper = Long.valueOf(s); // returns a Long object
long primitive = wrapper; // implicit unwrapping
If the string cannot be parsed, Long.valueOf also throws NumberFormatException.
solid conversion patterns
1. Validate before parsing
To avoid exceptions, you can first check whether the string matches a valid long pattern using a regular expression:
boolean isValid = input.matches("[+-]?\\d+");
if (isValid) {
long result = Long.parseLong(input);
// proceed
} else {
// handle invalid input
}
Note: The regex is a quick check; it does not guarantee that the value fits within the long range, but it filters out obvious non‑numeric strings Still holds up..
2. Use tryParse helper (Java 8+)
If you are on Java 8 or newer, you can take advantage of the Long class’s tryParse method (available via Long.parseLong in a try‑with‑resources style) or write a small utility:
public static long safeParse(String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Cannot convert \"" + s + "\" to long", e);
}
}
This wrapper re‑throws a more descriptive exception, making error handling clearer in larger code bases.
3. Dealing with locale‑specific decimal separators
parseLong expects a decimal point (.That's why if you have locale‑specific formats (e. ) and thousands separator (none). g.
String localized = "1.234,567"; // European format (dot as thousands, comma as decimal)
String normalized = localized.replace(".", "").replace(",", ".");
long value = Long.parseLong(normalized);
Be cautious: this approach works only when you know the exact format.
Common pitfalls and how to avoid them
| Pitfall | Why it happens | How to prevent |
|---|---|---|
| Overflow | The string represents a number larger than `Long.Think about it: | Use regex validation or Scanner with useDelimiter to isolate numbers. Which means |
| Non‑numeric characters | Embedded letters ("12a3") cause an exception. That's why mAX_VALUEor smaller thanLong. |
Ensure input is trimmed; if spaces are part of the data, replace them before parsing. That's why |
| Leading zeros | Strings like "000123" are accepted, but may confuse logic if you expect a specific format. On the flip side, mIN_VALUE`. |
|
| Locale‑dependent formatting | Using commas or periods incorrectly for decimal points. | |
| Whitespace issues | Unexpected spaces inside the number ("12 34") break parsing. |
Standardize the string to a canonical format before calling parseLong. |
Step‑by‑step guide to a safe conversion
- Obtain the string – e.g., from user input, file reading, or a database field.
- Trim whitespace –
String trimmed = s.trim(); - Validate format (optional but recommended) –
if (!trimmed.matches("[+-]?\\d+")) { /* invalid */ } - Parse –
long result = Long.parseLong(trimmed); - Handle exceptions – wrap in
try‑catchto manageNumberFormatException.
Full example method
public static long convertStringToLong(String input) {
if (input == null) {
throw new IllegalArgumentException("Input string cannot be null");
}
String cleaned = input.trim();
// Quick validation
if (!cleaned.matches("[+-]?
try {
return Long.parseLong(cleaned);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Parsed value out of long range: \"" + input + "\"");
}
}
Calling this method:
long qty = convertStringToLong(" -1050 "); // returns -1050
Performance considerations
The parseLong method is highly optimized and runs in constant time. Worth adding: g. But for bulk conversions (e. Day to day, , processing thousands of strings), the overhead is minimal. Still, avoid unnecessary object creation; prefer the primitive long return type over Long wrappers unless you specifically need the object.
Honestly, this part trips people up more than it should.
Frequently asked questions (FAQ)
Q1: Can I convert a string that contains commas, like "1,000"?
A: No. Long.parseLong does not recognize commas. Remove them first (replace(",", "")) or use a custom parser that handles the formatting.
Q2: What happens if the string is empty ("")?
A: A NumberFormatException is thrown because an empty string is not a valid numeric representation.
Q3: Is there a difference between Long.parseLong and Integer.parseLong?
A: Yes. Integer.parseLong expects values that fit into a 32‑bit int. Using it for numbers outside that range will also throw NumberFormatException. Always use Long.parseLong when the target type is long Small thing, real impact..
Q4: Can I convert a String that represents a hexadecimal number (e.g., "0xFF")?
A: Not with parseLong. Use Long.parseLong(hexString, 16) to specify radix 16.
Q5: How do I handle null inputs gracefully?
A: Check for null before calling parseLong and decide on a policy (e.g., return a default value, throw an exception, or return 0L) And that's really what it comes down to..
Conclusion
Converting a String to a long in Java is straightforward thanks to the built‑in Long.parseLong method, but a reliable implementation requires attention to validation, error handling, and potential overflow. But by trimming input, optionally validating the format with a regular expression, and wrapping the parsing call in a try‑catch block, you can safely transform textual numeric data into the primitive long type. Remember to consider locale‑specific formats and to use the primitive type for performance unless a wrapper object is required. With these practices, your Java programs will handle numeric string conversions reliably, reducing runtime errors and improving overall code quality.