How to Convert long to String in Java

How to Convert long to String in java

It is used if we have to display a long number in the text field because everything is displayed as a String. A long value can be converted into a String using any of the following methods:

  • Using String.valueOf() method
  • Using Long.toString() method
  • Using the Constructor of Long Class

Using String.valueOf(long l)

It is used to convert long to String. It is the static method of String class. This method takes long value as an argument and returns a string representation of it. The String.valueOf() is an overloaded method.The syntax of this method is-

Where l is the long value that is to be converted.

Example

Consider the following example; we have taken a long variable var having value 7823597L, where l denotes the long type. The String is a class. str is a variable that stores the converted value of var. The valueOf() is a built-in method of String class passing a variable var as an argument. The println statement prints the converted value of var.

Output

Using Long.toString(long l)

This method works same as String.valueOf() method. It returns the String that represents the long value that we pass to this method. This is the most common and popular method for converting a long to String. The sign will be preserved if the number is negative. The syntax of this method is-

Where l is the long value, we are passing to the method as an argument.

Example

Consider the following example, here we have taken variable num of type long having value 999999999L. The String is a class. str is a variable that stores the converted value of num. Long is a wrapper class. The toString() is a built-in method passing an argument num. The println statement prints the converted value of num.

Output

Using newLong(long).toString()

An alternative method is to create an instance of the Long class and then invoke it’s toString() method. It is a little less efficient than the first two methods shown above. Before conversion is performed, a new instance of the Long class is created.

The use of Long.toString() and String.valueOf() are ideal if the variable you want to convert is primitive (long). But if your variable is already an instance of Long (wrapper class of the primitive type long), it is better to just invoke its toString() method as shown in the code above. We can create a constructor in the following forms-

We can also write the above code as: 

or

Example 

In the following example; we have taken a variable val of type long having value 98757563L. String is a class. str is a variable that stores the converted value of num. The new keyword creates the constructor of Long class having val as an argument. The toString() is a built-in method. The println statement prints the converted value of val.

Output