I've seen in some java libraries when returning a string the value is concatenated with an empty value.
For example package java.io;
/**
* The system-dependent default name-separator character, represented as a
* string for convenience. This string contains a single character, namely
* <code>{@link #separatorChar}</code>.
*/
public static final String separator = "" + separatorChar;
Why not return only separatorChar?
Are strings the preferred datatype for return values? Give that this is only a char anyway why use a string datatype?
Are there any performance implications of doing this conversion?
One is a String
, the other is char
. It's useful to always be dealing with a String
, rather than having to check if it's a char
.
This is one of several ways of converting a char to a String. Although this used to be one of the slower ways of converting from char to String, as of java 6 update 20, with the introduction of -XX:+OptimizeStringConcat flag, concatenation is the fastest way to convert any value to string. As of Java 7, this option is turned on by default. So you're correct. There are performance implications. Here is a really great post which discusses this : https://stackoverflow.com/a/44485322/1028560.
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