r/learnjava • • Sep 23 '16

What does it mean when you use the single quotation for assigning values?

For example, double w='a'+5. Is 'a' referring to character a?

1 Upvotes

3 comments sorted by

2

u/[deleted] Sep 23 '16

Yes, it is referring to a char. But I think that a will be equal to a number in this context, because every character matches a specific number.

For example: A=1 and a=27

Not completely sure if it is this way.

2

u/desrtfx Sep 23 '16

Your statement about referring to a char is correct, the rest is wrong.

Java uses Unicode, a system in which each character is represented by a number.

The alphabet corresponds to the standard ASCII encoding, so 'A' has the number 65, and 'a' has the number 97 - as can be seen in the ASCII Table.

char values are internally stored as unsigned 16-bit integer numbers ranging from 0 to 65535 inclusive. Since they are numbers, arithmetic operations such as 'a' + 5 are allowed and working.

1

u/8igg7e5 Sep 23 '16

And the whole topic of Unicode and why Java has a 16-bit unsigned char is complex. The java 'char' type was created at a time when all unicode characters fitted in 16-bits. Alas Unicode is not a fixed standard, it evolves with language and as it consumes more and more representation of communication (consider all of hte emoticons added). As a result I believe it currently requires 32-bits to fully represent all Unicode characters.

So yes, a java char is really a number and 'a', (char) 97 and even '\u0061' are just representations of the same 16-bits. But a java char is not necessarily an entirely composed Unicode character - which is why String has length() (number of chars) and codePointCount(int, int) (number of full unicode characters).

I suspect, had Java been designed later, with platform support for value-types (as is planned for maybe Java 10) then char probably would have been a UTF-8 Unicode character and value-types would have been provided for larger compositions/representations but while the latter might happen later, for compatibility reasons Java will always have the 16-bit unsigned char as its 'character' type.

 

Note: My terminology may be off, I am far from an expert on Unicode.