5

Declaration of a character:

char ch = '';

When I do this i am getting the error 'empty character literal'.

Declaration of a String:

String str = "";

I see no error in doing that to a String.

The question is, why doesn't a similar error show up for the declaration of a String, or why declaration of empty character generating such error where empty string is getting passed

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
  • A string consists of zero or more characters. A cardboard box can contain zero or more oranges, and can be empty, but there's no such thing as an empty orange. – Louis Wasserman Sep 01 '15 at 20:37

5 Answers5

3

String is a set of chars and String str=""; contains no chars(read: empty string) but if you want to have Char variable it must have some value. '' means no value.

Jure Potocnik
  • 489
  • 7
  • 21
  • 4
    it can't be null; `char` is a primitive and must always have a value (although it can be unassigned, in which case it can not be accessed) – Bohemian Sep 01 '15 at 17:27
  • 3
    @Ratul no. Java strings are not like C strings. Java strings may contain nulls (hex `00`) - their length is managed in a separate field to the backing `char[]` – Bohemian Sep 01 '15 at 17:31
  • 1
    @RatulSharker in Java end of string isn't marked by null (ASCII 0) character. Instead it is implemented as `char[]` array, and all arrays have predefined length. – kajacx Sep 01 '15 at 17:32
1

String is a class in Java with its own syntax and methods. It accepts strings in double quotes. And a string is actually an Array of characters and is hence acceptable to be posted empty. Char on the other hand is a data type and cannot be left undetermined. It needs to specified NULL.

Sanved
  • 921
  • 13
  • 19
1

I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.

Basically char is a thing you put in a box, and a string is a box to hold all those things. You can have an empty box but not a non-existant thing.

javawocky
  • 899
  • 2
  • 9
  • 31
0

A string is an array of characters. By passing it nothing, i.e. making it equal to "" you basically make an empty array which is fine. But char is a primitive type hence it cannot be "empty". The closest you can get is setting it equal to '\0' which is the null character.

Zarwan
  • 5,537
  • 4
  • 30
  • 48
0

Here char represents the 16-bit integer value of the character in quotes. Refer this table for the values. There is no representation number for "empty/no character". In case of String refer their source code. You can see that empty string is represented internally by 0 size char array. So String internally does not have magical representation of empty/no character. For "" String class does not allocate any space per se

Saurabh
  • 7,894
  • 2
  • 23
  • 31