char Java Keyword with Examples

  1. The char keyword is used to declare character variable. 
  2. char is a Java primitive type. 
  3. In Java, the data type used to store characters is char. The char data type is a single 16-bit Unicode character.
  4. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
  5. The Wrapper Character class represents char primitive type as an object.

char Java Keyword Examples

Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
    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);
    }
}
This program displays the following output:
ch1 and ch2: X Y
Although char is designed to hold Unicode characters, it can also be used as an integer type on which you can perform arithmetic operations. 
For example, you can add two characters together, or increment the value of a character variable. Consider the following program:
// char variables behave like integers.
class CharDemo {
    public static void main(String args[]) {
        char ch1;
        ch1 = 'X';
        System.out.println("ch1 contains " + ch1);
        ch1++; // increment ch1
        System.out.println("ch1 is now " + ch1);
    }
}
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing Y, the next character in the ASCII (and Unicode) sequence.

Summary

  1. The following char constants are available:
  • \b − Backspace
  • \f − Form feed
  • \n − Newline
  • \r − Carriage return
  • \t − Horizontal tab
  • ' − Single quote
  • " − Double quote
  • " − Backslash
  1. The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
  2. The Wrapper Character class represents char primitive type as an object and which includes useful static methods for dealing with char variables, including isDigit(), isLetter(), isWhitespace() and toUpperCase().

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments