Why does Java require the char variable to use single quotes?

前端 未结 2 695
傲寒
傲寒 2021-01-14 14:33

Why is it that Java requires the char variable to enclose anything inside of it with single quotes rather than double? An example of this:

char s = \'s\'; //         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 14:52

    Because char and String are two different types, and how else is Java supposed to know whether you want a character or string of length 1?

    For example, given the methods:

    public void foo(String s) { }
    public void foo(char c) { }
    

    And the call

    foo("a");
    

    If characters could be made with double quotes, how would Java know which method to call?

提交回复
热议问题