简体   繁体   中英

why can't we set default value of char type variable to ' '

Why can't we set default value of char type variable to ' '? Likewise, we can set default value of string variable to " " in Java.

Suppose

class abc
{
   private String a="";
   private char b='';//here it will give error
}

Because '' is not a character literal as defined in the Java Language Specification .

CharacterLiteral:
    ' SingleCharacter '
    ' EscapeSequence '

SingleCharacter:
    InputCharacter but not ' or \

InputCharacter:
    UnicodeInputCharacter but not CR or LF

UnicodeInputCharacter:
    UnicodeEscape
    RawInputCharacter

UnicodeEscape:
    \ UnicodeMarker HexDigit HexDigit HexDigit HexDigit

UnicodeMarker:
    u
    UnicodeMarker u

RawInputCharacter:
    any Unicode character

HexDigit: one of
    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

On the other hand, a String literal is defined as

StringLiteral:
    " StringCharacters opt "

Notice the opt , for optional.

A string is basically an array of characters, and an array can be empty without any issues.

Since a character is not an array, it can't be empty, it has to be set to a valid 'character' value.

If You want to set char to be empty use:

Character c='\u0000'

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Try \\0. That would be a good substitute for the empty character primitive. These is no empty primitive character, it has to be something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM