简体   繁体   中英

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

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'; //This will not break

vs:

char s = "s"; //This will break

I understand that double quotes are primarily for strings but is there a specific reason as to why chars were built to only use single quotes and to break when a double quote is entered?

I have tried to do some research but the only thing that was relevant was another SO Question , which refers to the difference between single and double quotes, not the reasoning behind the syntactical development of the char.

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?

This is a question written by a person used to the modern easy scripting languages whose goal is to make programming easy to learn and fast to type.

Java is a language for people who know what the CPU does underneath. In the world of low level languages (assembley, C, Java etc.) a character is an integer (UTF may require more than one int) whereas a string is an array of integers. By allowing a programmer to define the exact variable type, Java allows you to write more efficient code.

But it also allows you to write String s = "s"; if you don't care about efficiency.

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