Convert Long to String in Java



Convert Long to String in Java | ninjasquad

In this tutorial, we’ll learn different methods to convert long primitive or Long object to String in Java

Convert long primitive to 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 first three methods i.e. Long.toString(), String.valueOf, and + are concise and good to use.

Convert Long object to 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 that first method i.e. longObj.toString() is the quickest and concise way to convert a Long object to String, followed by the next three methods.

Exception handling – Long to String

Let’s see how these methods handle the 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 highlighted methods return the “null” string for null value while others throw NullPointerException or IllegalArgumentException so you can use the method wisely.



Source: Internet

Leave a Comment

We are offering free coding tuts

X