A long is a 64-bit signed primitive data type in Java used to store large integer values. Converting a long to a String is useful when the numeric value needs to be displayed, concatenated with text, or processed as textual data.
- A long can be converted to String using built-in Java methods.
- String.valueOf() is a simple and commonly used approach.
Illustration
Input: Long = 20L
Output: "20"Input: Long = 999999999999L
Output: "999999999999"
Methods to Convert Long to String in Java
1. Using String.valueOf()
String.valueOf() converts the given long value into its string representation.
Syntax:
String str = String.valueOf(value);
public class Main {
public static void main(String[] args) {
long value = 999999999999L;
String str = String.valueOf(value);
System.out.println(str);
}
}
Output
999999999999
Explanation: The String.valueOf() method converts the long value into a String and stores the result in str.
2. Using Long.toString()
The Long.toString() method converts a long value into its string representation.
Syntax:
String str = Long.toString(value);
public class Main {
public static void main(String[] args) {
long value = 999999999999L;
String str = Long.toString(value);
System.out.println(str);
}
}
Output
999999999999
Explanation: Long.toString() directly converts the specified long value into a String.
3. Using String Concatenation
A long can also be converted to a String by concatenating it with an empty string.
public class Main {
public static void main(String[] args) {
long value = 999999999999L;
String str = "" + value;
System.out.println(str);
}
}
Output
999999999999
Explanation: When a long is concatenated with a String, Java converts the numeric value into a String automatically.
4. Using String.format()
String.format() can be used when the conversion is required as part of formatted output.
public class Main {
public static void main(String[] args) {
long value = 999999999999L;
String str = String.format("%d", value);
System.out.println(str);
}
}
Output
999999999999
Explanation: The %d format specifier formats the long value as a decimal integer and returns the result as a String.