1. The char type
Initializing chars
A char stores a single character, such as 'x'. More about char will be covered when we learn about strings. The important thing to remember is that a character is stored internally as a number, and that characters can be casted to ints easily. First, let's create some chars:
public class MyProgram { public static void main(String[] args) { char var = 'a'; //the variable var stores the character 'a' char a = 'x'; //the variable a stores the character 'x' //it is important to realize the variable name and the internal character can be different System.out.println(var); //prints the character a System.out.println(a); //prints the character x System.out.println('b'); //prints b } }
Casting chars to/from ints
The character 'a' is stored internally as the number 97. The character 'A' (capital A) is the number 65. We can find many of these on conversions on "ASCII Tables" and "Unicode Tabls" you can find on the internet. Indeed, these days there are many characters that computers can support besides those from English. The original 127 characters were part of the ASCII table, but many new characters such as those from Asian languages are part of the extended unicode table. Here's how to cast a character to an integer to find its numerical value:
public class MyProgram { public static void main(String[] args) { System.out.println( (int)'a' ); //prints 97. The spaces are here just for clarity char a = 'A'; System.out.println( (int)a ); //prints 65 System.out.println( ((int)'x') ); //some people like additional parenthesis, though not required System.out.println( (char)97 ); //prints the character 'a' System.out.println( (char)65 ); //prints the character 'A' } }
Special characters and Escape characters
Keys such as enter, space, and tab are also characters (10, 32, and 9). However, you can't put every character in single quotes to signify a char. For example, although println('a') works, println(''') does not, since Java thinks the second single quote is ending the char. Thus, to print a single quote, you actually need println('\''). Typing the slash in front of the single quote is called "escaping" the character, or creating an "escape sequence". Here are some more escape sequences:
public class MyProgram { public static void main(String[] args) { System.out.println('\t'); //a tab System.out.println('\b'); //a backspace (deletes the previous character printed!) System.out.println('\n'); //a new line character, used as a new line for Linux, MacOSX System.out.println('\r'); //a "carriage return". Windows uses a \r\n for new lines System.out.println('\''); //single quote System.out.println('\"'); //double quote System.out.println('\\'); //a backslash System.out.println("She said she \"literally\" ate my cat"); //Previous line prints: She said she "literally" at my cat } }