In this guide, we will discuss the following ways to convert a long value to a String:
- String.valueOf(long l) Method
- Long.toString(long l) Method
- String.format() Method
- Using DecimalFormat
- Using StringBuilder and StringBuffer
Note: Out of all these ways, the String.valueOf() is the preferred method for conversion as it is null safe. If the long value is null, the String contains "null" after conversion, instead of throwing NullPointerException.
1. Using String.valueOf() Method
We can use String.valueOf(long l) method to convert long to String. This method takes a long value as an argument and returns a string representation of it.
Method Syntax:
public static String valueOf(long l)
Parameters:l – long value that needs to be converted into a String
Returns:
String representation of long argument l.
long lvar = 123; String str = String.valueOf(lvar);
Java long to String Example using String.valueOf()
public class JavaExample{
public static void main(String args[]){
long l = 100000001L;
//long to String Conversion
String str = String.valueOf(l);
//Print String value
System.out.println("String after conversion: "+str);
}
}
Output: