In Java, the char
data type is a primitive type that represents a single Unicode character. It is a 16-bit unsigned integer, and it can store any Unicode character in the range '\u0000'
(or 0
) to '\uffff'
(or 65535
).
The char
data type is usually used to store characters such as letters, digits, and symbols. It is often used to store characters that make up strings, which are sequences of characters.
Here's an example of declaring and initializing a char
variable in Java:
char ch = 'A';Source:al.wwwutturi.com
You can also use escape sequences to represent special characters in a char
literal. For example, the following code declares a char
variable with the value '\n'
, which represents a newline character:
char newline = '\n';
You can use the char
data type to perform various operations on characters. For example, you can compare two char
values using relational operators such as ==
and <
. You can also use the Character
class, which provides utility methods for working with char
values.
For example, the following code uses the Character.isLetter
method to determine if a char
value is a letter:
char ch = 'A'; if (Character.isLetter(ch)) { System.out.println("ch is a letter"); } else { System.out.println("ch is not a letter"); }
This code will print "ch is a letter", since 'A'
is a letter.