Why does new String("") compile while char c = '' does not?

Why are empty Strings valid and empty chars are not ? I would have thought an empty String is not a string but just a placeholder. The same for a char, but creating an empty char does not even compile.

What im wondering is why the following occurs - Compiles -

String s = "";

Does not compile -

char c = '';

Solution 1:

Because char represents a single character, which '' isn't. A String can contain zero or more characters, but a character cannot be anything other than a single character.

Solution 2:

Because a string literal represents a String which may consist of zero or more characters, but a (valid) character literal represents exactly one character.


A char could be defined as a datatype that can store 0 or 1 characters ...

Yes. In theory it could have been defined that way. But trust me, if you think through all the issues (e.g. how you'd represent an empty char, how an application would deal with it, etc) you will conclude that the there are few benefits, and significant downsides.

Anyway, doing this merely so that there was a syntactic consistency between String and char literals would be totally crazy. You don't break a language's performance and/or semantics so that the syntax looks nice.


One comments on the accepted answer proposes that '' should mean the same as '\0'. But the counter argument to this is that '\0' does not mean no characters. It means one character whose value is zero. So if '' actually means one character it is misleading. And since there is already a way of denoting this ... '\0' ... a second way of denoting it is redundant.

If some piece of new language syntax is both misleading and redundant, it is hard to justify adding it.

In respose to SoloBold's comment, while it would be possible to define a character type to do that, it would require more space. At least 1 bit, and more likely 16 bits to avoid awkward memory alignment problems. A 32-bit char type would not be acceptable ... even though it does solve other problems.

Solution 3:

"" is an empty array of characters.

'' is simply not a character.

Solution 4:

An empty string is like a container that holds nothing. A char must have a value and without exactly one character there is no where to derive that value from.