So I just perused for a while, all the different questions on here about .valueOf
with strings, but they all seem to be about conversions. Comparing .valueOf
to just + ""
.
I want to know if it is worth it or at all necessary to use .valueOf
if it is a concatenation.
Example:
LOGGER.info("Final Score: " + String.valueOf(Math.round(finalScore * 100)) + "%");
VS
LOGGER.info("Final Score: " + Math.round(finalScore * 100) + "%");
It seems as though using String.valueOf
is unnecessary if you have actual strings to go along with it. I understand it may be better to use .valueOf
if you were just converting it and intended to use an empty string.
String. valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .
The source code for String#valueOf(Object)
looks like this:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
So the only difference between valueOf
and toString
is that valueOf
is null-safe. So let's see which one is used if we concatenate a string and an object.
Object foo = null;
System.out.println("foo " + foo); //foo null, no exception thrown
System.out.println("foo " + String.valueOf(foo)); //foo null, no exception thrown
So it looks like there's no difference whatsoever between concatenation and using valueOf
in this context.
When we concatenate strings, the compiler actually translates it to StringBuffer.append().
The underlying implementations for StringBuffer.append(int) and String.valueOf(int) both eventually end up calling Integer.getChars(int,int,char[]) except that in case of String.valueOf()
, there is a call to Integer.toString(int)
first.
To conclude, for the given scenario, directly concatenating would be the way to go. But if you intend to be conscious about memory, then use string-builder to concatenate values first and then log it.
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