Visit Sponsor

Written by 3:04 pm Core Java

Convert String to long in Java – Methods and Examples

Converting a String to a primitive long or a Long object in Java is a common task, especially when processing numeric input from the user, reading values from files, or parsing network responses. Java provides standard APIs that perform this conversion reliably with built-in error handling.

In this tutorial you will learn how to convert a Java String to the long type and the Long wrapper class in a safe, efficient way.

When You Need to Convert a String to long

Typical scenarios include:

  • Parsing numerical IDs entered as text
  • Reading numeric values from configuration or properties
  • Processing numerical input in command-line, GUI, or web applications

Method 1: Using Long.parseLong(String)

Long.parseLong() converts a numeric string directly into a primitive long. This is the simplest and most common method.

Example

String numberStr = "1234567890";
long result = Long.parseLong(numberStr);
System.out.println("Converted long: " + result);

Notes

  • Accepts only valid numeric representations
  • Throws NumberFormatException if the string contains non-digit characters

Method 2: Using Long.valueOf(String)

Long.valueOf() returns a Long object rather than a primitive. It is useful when working with collections or APIs that expect wrapper types.

Example

String numberStr = "9876543210";
Long resultObj = Long.valueOf(numberStr);
long primitive = resultObj.longValue();
System.out.println("Converted Long object: " + resultObj);

Notes

  • Internally uses Long.parseLong() and wraps the result
  • Preferred when you need an object rather than a primitive

Handling Invalid Input Safely

When parsing user input or external data, always catch exceptions to avoid runtime crashes.

Example with Exception Handling

String input = "12ab34";

try {
    long value = Long.parseLong(input);
    System.out.println("Parsed value: " + value);
} catch (NumberFormatException e) {
    System.err.println("Invalid number: " + input);
}

Best Practices

  • Validate input before parsing when possible
  • Provide user-friendly error messages or fallbacks
  • Avoid parsing unchecked strings without try/catch

Converting With a Default Value

To avoid exceptions and provide a default when parsing fails:

public static long toLongOrDefault(String str, long defaultValue) {
    try {
        return Long.parseLong(str);
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

// Usage
long val = toLongOrDefault("abc", 0L);

This pattern is useful in configuration parsing and batch processing.

Converting a String with Radix/Base

If you have numeric strings in non-decimal formats (e.g., hex), use:

String hexStr = "1A3F";
long hexValue = Long.parseLong(hexStr, 16);
System.out.println("Hex value: " + hexValue);

This supports bases from 2 to 36.

Avoiding NullPointerException

Always check for null before conversion:

String str = null;

if (str != null) {
    long val = Long.parseLong(str);
} else {
    // handle null value
}

Passing a null string to parseLong() causes NullPointerException.

Summary of Methods

MethodReturnsThrows if invalidNotes
Long.parseLong(String)longYes (NumberFormatException)Fastest for primitives
Long.valueOf(String)LongYes (NumberFormatException)Useful when object type needed
Custom fallbacklongNo (handled)Provides default values

Best Practices (Senior Engineering Insight)

  • Always guard parsing with try/catch for robust applications
  • Use helper methods for repeated parsing logic
  • Validate input formats where possible before conversion
  • Avoid parsing unchecked external input directly in business logic

These practices help prevent unhandled exceptions and improve application stability.

Visited 6 times, 1 visit(s) today
Close