This example shows how to convert long to string in Java using the toString, valueOf, and + operator. It also shows the best way to convert long to string.
How to convert long to String in Java?
1) Convert long to string using the String class
You can use the valueOf
static method of the String class.
1 |
static String valueOf(long l) |
The valueOf
method returns a string representation of the long argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.basic; public class LongToStringExample { public static void main(String[] args){ long l = 21343131L; String strNumber = String.valueOf(l); System.out.println("String value: " + strNumber); } } |
Output
1 |
String value: 21343131 |
2) Using the Long wrapper class
We can also use the toString
method of the Long wrapper class to convert.
1 |
public static String toString(long l) |
This method returns a string representation of the long value passed as a parameter.
1 2 3 |
long l = 21343131L; String strNumber = Long.toString(l); System.out.println("String value: " + strNumber); |
Output
1 |
String value: 21343131 |
3) Using String concatenation
String concatenation can be indirectly used to convert any Java primitive values to a string as given below.
1 2 3 |
long l = 21343131L; String strNumber = "" + l; System.out.println("String value: " + strNumber); |
Output
1 |
String value: 21343131 |
What is the best way to convert?
The valueOf
method of the String class internally calls the toString
method of the Long wrapper class to convert. Using either of the methods is equally efficient in terms of performance. The preferred way is to use the toString
method of the 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 the code statement is conversion.
b) String concatenation operation creates unnecessary temporary objects during the conversion process. String concatenation is achieved using the append
method of the StringBuffer or StringBuilder class. So the code,
1 |
String strNumber = "" + l; |
Will run like,
1 2 3 4 5 6 |
StringBuilder sb = new StringBuilder(); sb.append(""); sb.append(l); String strNumber = sb.toString(); |
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.