The char keyword is a data type. You can store a character such as ‘A’, ‘a’ etc to the char variable.
Important Points:
- The value assigned to a char data type is provided in single quotes such ‘Q’, ‘h’ etc.
- You can also pass integer numbers ranging from 0 to 65,535 to a char variable, these values are treated as ASCII characters. For example, passing 72 value to a char type variable will print ‘H’, if you print the value of that variable.
- It is a single 16-bit unicode character. The min value is
'\u0000'
(or 0) and max value is'uffff'
(or 65,535).
Example of char Keyword
public class JavaExample { public static void main(String[] args) { char ch1 = 'A'; char ch2 = 'p'; System.out.println(ch1); System.out.println(ch2); } }
Output:
A p
Example 2: Passing ASCII value to char type variable
public class JavaExample { public static void main(String[] args) { char ch1 = 72; char ch2 = 125; System.out.println(ch1); //prints 'H' System.out.println(ch2); //prints '}' } }
Output: