Java Basic Examples

Java convert long to String example

This example shows how to convert long to String in Java. This example also shows how to convert long to String using several methods and the best way among them.

How to convert long to String in Java?

There are several ways in which primitive long can be converted to String in Java.

1) Convert long to String using String class

Use valueOf static method of String class to convert long to String.

valueOf method returns String representation of long argument.

Output

2) Convert long to String using Long wrapper class

Use toString method of Long wrapper class to convert from long to String in Java.

This method returns String representation of long value passed as a parameter.

Output

3) Convert long to String using String concatenation

String concatenation can be indirectly used to convert Java primitive values to String as given below.

Output

What is the best way to convert long to String?

valueOf method of String class internally calls the toString method of Long wrapper class to convert from long to String value. Using either of the methods is equally efficient in terms of the performance. Preferred way is to use toString method of Long wrapper class.

String concatenation should be avoided mainly for the conversion purpose because,

a) It is difficult to visually understand that the intent of code statement is conversion.

b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using StringBuffer’s or StringBuilder’s append method. So the code,

Will run like,

Please let us know your views in the comments section below.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags