Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.