Date:

Share:

Convert Long to String in Java

Related Articles

In this tutorial, we will learn different methods of conversion long Primitive or long String object in Java

A long primitive convert to a string

String s1 = Long.toString(1L); // "1"
String s2 = String.valueOf(1L);  // "1"
String s3 = "" + 1L; // "1"

String s4 = new StringBuilder().append(1L).toString(); // "1"
String s5 = String.format("%d", 1L); // "1"
String s6 = new DecimalFormat("#").format(1L); // "1"

We see that the first three methods i.e. Long.toString(), String.valueOf, And + They are concise and good to use.

Convert a long object to a string

Long longObj = 1L;

String s1 = longObj.toString();  // "1"

String s2 = Long.toString(longObj); // "1"
String s3 = String.valueOf(longObj);  // "1"
String s4 = "" + longObj; // "1"

String s5 = new StringBuilder().append(longObj).toString(); // "1"
String s6 = String.format("%d", longObj); // "1"
String s7 = new DecimalFormat("#").format(longObj); // "1"

We see the first method i.e. longObj.toString() Is the fastest and most concise way to convert a long object to a string, followed by the following three methods.

Exception Handling – Long to String

Let’s see how these methods cope null value:-

Long longObj = null;

String s1 = longObj.toString();  // throw "NullPointerException"
String s2 = Long.toString(longObj); // throw "NullPointerException"
String s3 = String.valueOf(longObj);  // throw "IllegalArgumentException"

String s4 = "" + longObj; // "null"
String s5 = new StringBuilder().append(longObj).toString(); // "null"
String s6 = String.format("%d", longObj); // "null"

String s7 = new DecimalFormat("#").format(longObj); // throw "IllegalArgumentException"

We see that bold methods return the “null” string for null Value while others throw NullPointerException or IllegalArgumentException So you can use the method wisely.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles