1. Overview
In this short tutorial, weβll learn how to convert Long to String in Java.
2. Use Long.toString()
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.
3. Use String.valueOf()
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.
4. Use String.format()
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.
5. Use toString() Method of Long Object
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.
6. Using the + Operator
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.
7. Use StringBuilder or StringBuffer
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.
8. Use DecimalFormat
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.
9. Conclusion
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.
