Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why concatenate strings with an empty value before returning the value?

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?

like image 807
Lance Avatar asked Jan 25 '23 23:01

Lance


2 Answers

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.

like image 57
Michael Bianconi Avatar answered Jan 30 '23 04:01

Michael Bianconi


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.

like image 41
Sanjeev Avatar answered Jan 30 '23 03:01

Sanjeev