Declaring and initializing char variables

char c1 = 'a';
char c2 = 98;

System.out.println(c1);  // prints a
System.out.println(c2);  // prints b

char c3 = -1;            // compile time error

Java uses Unicode to represent char values. Setting a char variable to an int that corresponds to a Unicode character is equivalent to setting the variable to that character. Setting a char variable to an int value that does not represent a Unicode character results in a compile time error.

Converting between char and int

char letter = 'A';
int unicode = letter;
System.out.println(unicode);      // prints 65

int otherUnicode = 98;
char otherLetter = (char) otherUnicode;
System.out.println(otherLetter);  // prints b

Storing the value of letter in unicode does not require a cast. All possible Unicode values can be stored in a variable of type int.

Storing the value of otherUnicode in otherLetter requires a cast. It is possible to store values in otherUnicode that do not correspond to Unicode characters.

Operations with char values

char letter1 = 'A';
System.out.println(letter1 + 2);  // prints 67

char letter2 = 'B';
letter2 = (char) (letter2 + 2);
System.out.println(letter2);      // prints D

char letter3 = 'C';
letter3 += 2;
System.out.println(letter3);      // prints E

An operation performed on a char value is actually performed on the Unicode value.

The Unicode value of 'A' is 65. 65 + 2 is 67.

The Unicode value of 'B' is 66. 66 + 2 is 68. 68 is the Unicode value of 'D'.

The += operator can be used to avoid the cast when the left hand operand is a char. The -=, ++, and -- operators work similiarly.

System.out.println('a' + 'b');  // prints 195
System.out.println("a" + "b");  // prints ab

When both operands are of type char, the + operator acts as addition. The Unicode value of 'a' is 97. The Unicode value of 'b' is 98. 97 + 98 is 195.

"a" is of type String. See Working with String objects for more details.

Comparing char values for equality

char letter = 'a';

System.out.println(letter == 'a');  // prints true
System.out.println(letter == 'b');  // prints false
System.out.println(letter == 'A');  // prints false
System.out.println(letter != 'h');  // prints true

char values are compared for equality using the == operator and for inequality using the != operator.

Comparing char values for order

char c = /* value not shown */;

if(c >= 'A' && c <= 'Z')
    System.out.println("uppercase letter");
else
    System.out.println("not uppercase letter");

When the comparison operators are used with char values, the Unicode values are compared. The example above correctly checks if the value of c is an uppercase letter.

The condition can also be written as c >= 65 && c <= 90.

Looping through char values

for(char letter = 'a'; letter <= 'z'; letter += 2)
    System.out.print(letter);

The example above prints acegikmoqsuwy.

Additional resources

Java Primitive Data Types (Oracle)

Comments

Comment on Working with char values