
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
In this short tutorial, we’ll learn how to convert Long to String in Java.
For example, suppose we have two variables of type long and Long (one of primitive type and the other of reference type):
long l = 10L;
Long obj = 15L;
We can simply use the toString() method of the Long class to convert them to String:
String str1 = Long.toString(l);
String str2 = Long.toString(obj);
System.out.println(str1);
System.out.println(str2);
The output will look like this:
10
15
If our obj object is null, we’ll get a NullPointerException.
We can use the valueOf() method of the String class to achieve the same goal:
String str1 = String.valueOf(l);
String str2 = String.valueOf(obj);
When obj is null, the method will set str2 to “null” instead of throwing a NullPointerException.
Besides the valueOf() method of the String class, we can also use the format() method:
String str1 = String.format("%d", l);
String str2 = String.format("%d", obj);
str2 will also be “null” if obj is null.
Our obj object can use its toString() method to get the String representation:
String str = obj.toString();
Of course, we’ll get a NullPointerException if obj is null.
We can simply use the + operator with an empty String to get the same result:
String str1 = "" + l;
String str2 = "" + obj;
str2 will be “null” if obj is null.
StringBuilder and StringBuffer objects can be used to convert Long to String:
String str1 = new StringBuilder().append(l).toString();
String str2 = new StringBuilder().append(obj).toString();
str2 will be “null” if obj is null.
Finally, we can use the format() method of a DecimalFormat object:
String str1 = new DecimalFormat("#").format(l);
String str2 = new DecimalFormat("#").format(obj);
Be careful because if obj is null, we’ll get an IllegalArgumentException.
In summary, we’ve learned different ways to convert Long to String in Java. It’s up to us to choose which method to use, but it’s generally better to use one that’s concise and doesn’t throw exceptions.