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
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.
Java long to String. We can convert long to String in java using String. valueOf() and Long. toString() methods.
There are basically three methods to convert long to int: By type-casting. Using toIntExact() method. Using intValue() method of the Long wrapper class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With