简体   繁体   中英

Character literal in Java?

So I just started reading "Java In A Nutshell", and on Chapter One it states that:

"To include a character literal in a Java program, simply place it between single quotes" ie

char c = 'A'; 

What exactly does this do^? I thought char only took in values 0 - 65,535. I don't understand how you can assign 'A' to it?

You can also assign 'B' to an int?

int a = 'B'

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

I apologise if this is a stupid question.

My whole life has been a lie.

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

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

If you look at an ASCII chart, the character "A" has a value of 41 hex or 65 decimal. Using the ' character to bracket a single character makes it a character literal. Using the double-quote ( " ) would make it a String literal.

Assigning char someChar = 'A'; is exactly the same as saying char someChar = 65; .

As to why, consider if you simply want to see if a String contains a decimal number (and you don't have a convenient function to do this). You could 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;
    }
}

In Java char literals represent UTF-16 (character encoding schema) code units. What you got from UTF-16 is mapping between integer values (and the way they are saved in memory) with corresponding character (graphical representation of unit code).

You can enclose characters in single quotes - this way you don't need to remember UTF-16 values for characters you use. You can still get the integer value from character type and put if for example in int type (but generally not in short, they both use 16 bits but short values are from -32768 to 32767 and char values are from 0 to 65535 or so).

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