Java - Data Types char type

What is char type?

Java char data type is a 16-bit unsigned primitive data type.

char type represents a Unicode character.

char type is an unsigned data type. A char variable cannot have a negative value.

The range of the char data type is 0 to 65535, which is the same as the range of the Unicode set.

char literal

A character literal represents a value of the char data type.

A character literal in Java can be expressed in the following formats:

  • A character enclosed in single quotes
  • A character escape sequence
  • A Unicode escape sequence
  • An octal escape sequence
  • The following snippet of code assigns values to char variables using single quotes.
char c1 = 'A'; 
char c2 = 'a'; 
char c3 = '5'; 
char c4 = '@'; 

Characters enclosed in double quotes is a String literal. You cannot mix char type and String type.

char c1 = 'A';     // OK 
String s1 = 'A';   // An error. Cannot assign a char 'A' to a String s1 
String s2 = "A";   // OK. "A" is a String assigned to a String variable 
String s3 = "ABC"; // OK. "ABC" is a String literal 
char c2 = "A";     // An error. Cannot assign a String "A" to char c2 
char c4 = 'AB';    // An error. A character literal must contain only one character