2

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.

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
amped247
  • 93
  • 7

4 Answers4

8

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.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
4

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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

Its just to differentiate between a single character and a String. This method started with C and is continued to java.

anirudh
  • 4,116
  • 2
  • 20
  • 35
1

'' 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.

BigBerger
  • 1,765
  • 4
  • 23
  • 43