W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
在Java中,char存儲字符。Java使用Unicode來表示字符。Unicode可以表示在所有人類語言中找到的所有字符。
Java char是16位類型。
字符的范圍是 0
到 65,536
。沒有負(fù)字符。
Java中的字符是Unicode字符集的索引。字符表示在一對單引號內(nèi)。例如,'a'
,'z'
和'@'
。
這里是一個程序,演示char變量:
public class Main { public static void main(String args[]) { char ch1, ch2; ch1 = 88; // code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2);//ch1 and ch2: X Y } }
上面的代碼生成以下結(jié)果。
ch1
被分配值88,它是對應(yīng)于字母 X
的ASCII(和Unicode)值。
char
類型值可以用作整數(shù)類型和您可以執(zhí)行算術(shù)運(yùn)算。
public class Main { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1);//ch1 contains X ch1 = (char)(ch1 + 1); // increment ch1 System.out.println("ch1 is now " + ch1);//ch1 is now Y } }
上面的代碼生成以下結(jié)果。
下面的代碼顯示我們可以為非字母字符賦值Java字符類型。
public class Main { public static void main(String[] argv) { char ch = 'a'; System.out.println("ch is " + ch);//ch is a ch = '@'; System.out.println("ch is " + ch);//ch is @ ch = '#'; System.out.println("ch is " + ch);//ch is # ch = '$'; System.out.println("ch is " + ch);//ch is $ ch = '%'; System.out.println("ch is " + ch);//ch is % } }
上面的代碼生成以下結(jié)果。
以下代碼將unicode值存儲到char變量中。unicode文字使用 \\uxxxx
格式。
public class Main { public static void main(String[] args) { int x = 75; char y = (char) x; char half = "\\u00AB"; System.out.println("y is " + y + " and half is " + half); } }
上面的代碼生成以下結(jié)果。
轉(zhuǎn)義序列用于輸入不可能直接輸入的字符。
轉(zhuǎn)義字符值的語法:
'\''
用于單引號字符。'\n'
用于換行符。
對于八進(jìn)制符號,請使用反斜杠,后跟三位數(shù)字。例如,'\141'
是字母'a'。
對于十六進(jìn)制,您輸入反斜杠-u( \u
),然后輸入正好四個十六進(jìn)制數(shù)字。例如,'\u0061'
"是ISO-Latin-1 'a'
,因?yàn)轫敳孔止?jié)為零。 '\ua432'
是日語片假名字符。
public class Main { public static void main(String[] argv) { char ch = '\''; System.out.println("ch is " + ch);//ch is ' } }
字符是一個簡單的包裝器。
上面的代碼生成以下結(jié)果。
下表顯示了字符轉(zhuǎn)義序列。
轉(zhuǎn)義序列 | 描述 |
---|---|
\ddd | 八進(jìn)制字符(ddd) |
\uxxxx | 十六進(jìn)制Unicode字符(xxxx) |
\' | 單引號 |
\" | 雙引號 |
\\ | 反斜杠 |
\r | 回車 |
\n | 換行 |
\f | 換頁 |
\t | 轉(zhuǎn)義字符 |
\b | 退格 |
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: