Character literal in Java?

So, I just started reading "Java In A Nutshell", and the first chapter says that:

"To include a character literal in a Java program, simply put it between single quotes," that is.

char c = 'A'; 

What exactly does this do? I thought that char took only the values ​​0 - 65535. I do not understand how you can assign it an β€œA”?

Can you also assign 'B' to int?

 int a = 'B' 

The output for 'a' is 66. Where / why would you use the operation described above?

Sorry if this is a stupid question.

My whole life has been a lie.

+8
java
source share
3 answers

char is actually an integer type. It stores the 16-bit Unicode integer value of the corresponding character.

You can look at something like http://asciitable.com to see different meanings for different characters.

+10
source share

If you look at the ASCII diagram, the character "A" has a value of 41 hex or 65 decimal. Using the character ' to bind a single character makes it a character literal. Using double-quote ( " ) will make it a string literal.

Purpose char someChar = 'A'; exactly the same as char someChar = 65; .

As for why, think about whether you just want to see if String contains a decimal number (and you don't have a convenient function for this). You can use something like:

 bool isDecimal = true; for (int i = 0; i < decString.length(); i++) { char theChar = decString.charAt(i); if (theChar < '0' || theChar > '9') { isDecimal = false; break; } } 
+2
source share

In Java char literals are UTF-16 (character encoding) codes. What you received from UTF-16 is a comparison of integer values ​​(and how to store them in memory) with the corresponding character (graphical representation of the unit code).

You can enclose characters in single quotation marks - this way you do not need to remember the UTF-16 values ​​for the characters you use. You can still get the integer value from the character type and put it, if, for example, into the int type (but usually it’s not, they use 16 bits, but short values ​​are from -32768 to 32767, and char values ​​are from 0 to 65535 or so).

+2
source share

All Articles