Is there a specific reason ' '
is used for char
in Java programming?
It may be a stupid question, but I would like to know exactly why.
Is there a specific reason ' '
is used for char
in Java programming?
It may be a stupid question, but I would like to know exactly why.
Because a string
uses double quotes and it needs to differentiate between a char
and a string
.
Just the same as it requires you adding an L
for long
and an f
for float when specifying numbers - it needs to be able to determine which type you are referring to.
This is a very good article on declaring string literals in Java.
If your question is,
Why not use the double quote both for String and char?
then the answer is unambiguous: 'a'
is a completely different thing than "a"
.
If, on the other hand, your question is more on the line of
Why did Java choose to use the single quote for char, instead of something which I would prefer?
then there is no unique (or interesting) answer. The original designers of Java chose the single quote; for comparison, Rich Hickey chose a backslash prefix for Clojure and it works just as well.
Its just to differentiate between a single character and a String. This method started with C
and is continued to java
.
''
is used for Characters for the main reason of differentiating between Strings (Which use ""
instead of ''
).
A cool little trick to remember which type uses which type of quotation, remember how Strings can have more than one Character in them (Which is why they use a 'double' quote). Characters on the other hand, are basically an integer value that can be displayed as a single character (Essentially a letter) which is why they have the 'single' quote.