Home >Java >javaTutorial >How to assign value to char in java
There are two ways to assign values to the char type in Java: directly assigning character literals or using Unicode code points. Character literals use single quotes to enclose characters, and Unicode code points are represented using backslashes followed by the hexadecimal code. For example, ch1 = 'a' assigns ch1 to the lowercase letter "a", while ch3 = '\u0061' also assigns ch3 to the lowercase letter "a" but uses Unicode code point 0061.
Char assignment in Java
In Java, the char type is used to represent a single character. There are two ways to assign a value to a char variable:
Direct assignment
Use character literals to directly assign a value to a char variable. Character literals are enclosed in single quotes (').
<code class="java">char ch1 = 'a'; // 赋值为小写字母 "a" char ch2 = '7'; // 赋值为数字 "7"</code>
Unicode code points
Use Unicode code points to assign values to char variables. A Unicode code point is a hexadecimal number that represents the code corresponding to a character in the Unicode character set. To use a Unicode code point, use a backslash (\u) followed by the code point.
<code class="java">char ch3 = '\u0061'; // 赋值为小写字母 "a",代码点为 0061 char ch4 = '\u0037'; // 赋值为数字 "7",代码点为 0037</code>
Example
<code class="java">public class CharExample { public static void main(String[] args) { char ch1 = 'a'; char ch2 = '7'; char ch3 = '\u0061'; char ch4 = '\u0037'; System.out.println("ch1: " + ch1); // 输出: a System.out.println("ch2: " + ch2); // 输出: 7 System.out.println("ch3: " + ch3); // 输出: a System.out.println("ch4: " + ch4); // 输出: 7 } }</code>
The above is the detailed content of How to assign value to char in java. For more information, please follow other related articles on the PHP Chinese website!