Java long to String

In Java, you can convert a long to a String in several ways. Here are the most common methods:

1. String.valueOf()

The String.valueOf() method is one of the simplest and most commonly used methods to convert a long to a String. It converts the long to its string representation.

Example:


public class LongToStringExample {
    public static void main(String[] args) {
        long num = 12345678987L; //L is the suffix for long  
        
        // Convert long to String using String.valueOf()
        String str = String.valueOf(num);
        
        System.out.println("Converted String: " + str);
    }
}

Output: Converted String: 12345678987

Explanation:

String.valueOf(num) converts the long value num to a String.

2. Long.toString()

The Long.toString() method is another way to convert a long to a String. This method is part of the Long class.

Example:


public class LongToStringExample {
    public static void main(String[] args) {
        long num = 123987654321L; //L is the suffix for long
        
        // Convert long to String using Long.toString()
        String str = Long.toString(num);
        
        System.out.println("Converted String: " + str);
    }
}

Output: Converted String: 123987654321

Explanation:

Long.toString(num) converts the long value num to a String.

3. String Concatenation

In Java, you can also convert a long to a String by concatenating it with an empty string (“”). This is a quick and simple method but may not be as clear or efficient as the other methods for large or complex applications.

Example:


public class LongToStringExample {
    public static void main(String[] args) {
        long num = 123456789876L; //L is the suffix for long
        
        // Convert long to String using concatenation
        String str = num + "";
        
        System.out.println("Converted String: " + str);
    }
}

Output: Converted String: 123456789876

Explanation:


num + "" converts the long value num to a String by concatenating it with an empty string.

4. String.format()

You can also use String.format() to convert a long to a String. This is especially useful if you want to format the long value in a specific way (e.g., padding with leading zeros).

Example:


public class LongToStringExample {
    public static void main(String[] args) {
        long num = 123456789876L; //L is the suffix for long
        
        // Convert long to String using String.format()
        String str = String.format("%d", num);
        
        System.out.println("Converted String: " + str);
    }
}

Output: Converted String: 123456789876

Explanation:


String.format("%d", num) formats the long value num as a string. The %d is a format specifier for integers, and it will be used to convert the long to a string.