4

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?

2
  • 6
    It's a way of abusing the concatenation operator to turn arbitrary types into a String. In this case a char. Why they didn't just use Character.toString I don't know. Commented Aug 14, 2019 at 20:34
  • 2
    @BoristheSpider Or String.valueOf(char). Commented Aug 14, 2019 at 20:36

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.