Java long to String With Examples

Today we will see different ways to convert long to string in java. Java long to string conversion can be done in many ways, we will go through them one by one with example code snippets.

Java Long to String

 

Let’s look at different code snippets for java long to string conversion. Note that long is a primitive data type whereas Long is an Object. However java supports autoboxing, so they both can be used interchangeably in most of the cases.

  1. Using + operator

    This is the easiest way to convert long to string in java.

  2. Long.toString()

    We can use Long class toString method to get the string representation of long in decimal points. Below code snippet shows you how to use it to convert long to string in java.

    We can write long in other formats too such as Octal and Hexadecimal, let’s see what happens when we convert long to string in those scenarios.

    So the string is always being returned in decimal format. Let’s look into other ways to convert long to string too.

  3. String.valueOf()

  4. new Long(long l)

    Long constructor with long argument has been deprecated in Java 9, but you should know it.

  5. String.format()

  6. DecimalFormat

  7. StringBuilder, StringBuffer

    We can use StringBuilder and StringBuffer append function to convert long to string.

Java Long to String Example

Here is a simple program where we will convert long to string and print it using all the different methods we saw above.

Change the long value in above program to Octal or Hexadecimal format, you will notice that string representation is always on decimal format.

Convert Long to String with Radix

What if we want to convert long to string with different radix, not the default decimal point. We can use Long class methods for these cases. Below code snippet shows how to get the string representation of a long variable in different bases such as Octal, Hex or even custom one.

That’s all for converting long to string in java program.

Reference: Long API Doc

By admin

Leave a Reply

%d bloggers like this: