Java's Primitive Data Type: char

Introduction to the Primitive Data Type char


The charAt() Method


Comparing chars

Whereas Strings are usually compared using the .equals() method, characters in java need to be compared using the == or != operators, as demonstrated in this video:


Comparing Characters in Java

Characters Are Treated as Numbers in Java

In the video, below, we see that java treats characters as numbers. This can be annoying because using the + operating will cause the values of the characters to add instead of concatenate, which is often what we want. The video demonstrates how the use of double quotes ("") can be used to enforce concatenation.



Using char as an Array Index

In tthis example , we see that java's treatment of characters as numbers can also come in handy. For example, we can use characters as indices to an array:

char[] a = new char[256];   // ASCII only has a maxmium of 256 values
char theChar = 'x';  
System.out.println (a[theChar]); 

Converting a String to a char Array