Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to convert long to String in Java

Tags:

java

I've been using

long a = 123456789;
String b = a+"";

to convert a long value (or int) to String, or in this perspective, treat it as String. My question is, is it ok to do this? Are there any negative impact?

And is there any difference in using String.valueOf() vs Long.toString()?

Thanks

like image 645
Matthew Avatar asked Jul 22 '15 06:07

Matthew


People also ask

How do you parse a long into a string?

There are three main ways to convert a long value to a String in Java e.g. by using Long. toString(long value) method, by using String. valueOf(long), and by concatenating with an empty String. You can use any of these methods to convert a long data type into a String object.

Can you cast long to string java?

Java long to String. We can convert long to String in java using String. valueOf() and Long. toString() methods.

What is the correct way to cast a long to an int?

There are basically three methods to convert long to int: By type-casting. Using toIntExact() method. Using intValue() method of the Long wrapper class.


2 Answers

It is ok to do this as recent JVM will likely reduce it to:

String b = String.valueOf(a);

As for negatives, it is not good Java coding style as there is ambiguity. If a was null, would b = "null"? or will an NPE be thrown? You know the answer with experience, but this should be obvious to all readers of your code.

like image 99
daz Avatar answered Sep 26 '22 15:09

daz


First, your code doesn't compile - you have to append an L after the literal:

Long a = 123456789L;

String.valueOf() and Long.toString() methods both have a primitive long as a parameter, but since a is an wrapper (Long), you can just use the Object#toString() method:

String b = a.toString();

If a, however, is a primitive (long), both String.valueOf() and Long.toString() will do the same, so it's a matter of preference which one to use.

like image 44
Konstantin Yovkov Avatar answered Sep 23 '22 15:09

Konstantin Yovkov