Converting Java Long Values to Strings: Techniques and Examples

A long primitive in Java can represent a 64-bit signed integer. When building APIs, generating logs, or constructing display messages, you often need to convert a long into its textual representation. Several standard techniques exist, each with minor differences in behavior and performance characteristics.

Direct Conversion Using Wrapper Utilities

The most straightforward way involves the Long wrapper class or the String utility methods. Both rely on internal mechanisms that produce a decimal string.

public class LongConversionDemo {
    public static void main(String[] args) {
        long invoiceId = 9876543210L;

        // Option A: Long.toString() static factory
        String idAsText = Long.toString(invoiceId);
        System.out.println("Long.toString: " + idAsText);

        // Option B: String.valueOf() overload
        String idAsText2 = String.valueOf(invoiceId);
        System.out.println("String.valueOf: " + idAsText2);
    }
}

Both approaches call the same internal logic and hendle the full range of long values without loss.

String Building Through Concatenation or Buffers

If you are already assembling a larger string, appending a long to a StringBuilder or using the concatenation operator avoids an intermediate variable.

long sessionId = 4815162342L;
StringBuilder buffer = new StringBuilder();
buffer.append("Session: ");
buffer.append(sessionId);
String composite = buffer.toString();
System.out.println(composite);

The StringBuilder.append(long) method converts the number internally using Long.getChars, which is also what the simpler methods delegate to.

Formatting with Control Over Radix or Padding

When you need hexadecimal, octal, or zero‑padded output, String.format and specialized Long methods become useful.

long colorCode = 255;
String hex = Long.toHexString(colorCode);              // "ff"
String padded = String.format("%016d", invoiceId);     // zero-padded to 16 digits
System.out.println("Hex: " + hex + " | Padded: " + padded);

Relationship Between Types

The conversion process maps a numeric domain into its string representation.

erDiagram
    PrimitiveLong ||--|| TextString : "toString()"

Choosing an Approach

  • Default decimal conversion – Use Long.toString() or String.valueOf(). They are equivalent in behavior.
  • Within a larger concatenation – Append direct to a StringBuilder.
  • Non‑decimal bases, padding, or locale‑specific formatting – Use Long.toHexString(), Long.toOctalString(), or String.format with the appropriate specifier.

All these methods guarantee lossless conversion from long to String because every possible long value has a unique decimal representation that fits within the JVM’s string memory limits.

Tags: java Long string conversion Type Casting StringBuilder

Posted on Fri, 04 Sep 2026 16:07:11 +0000 by ojsimon