Character type data
Topics
Advertisements
Character type data:
Note: The character is defined as a letter, a digit or any special symbol enclosed within single quotes. For example, 'A' , 't' , '9', '?', '*' , etc. Assigning character literals to a variable A character variable is declared under char data type. Syntax: char variable name = <Character literal>
1. Input a Character
Note: There are two ways to input a character to a computer.
A. By using Scanner class: First, import “java.util.*”. Then, create a Scanner object to read input: “Scanner in = new Scanner(System.in);”. Finally, use “char ch = in.next().charAt(0);”
B. By using lnputStreamReader class:
First, import “java.io.*”. Then, create InputStreamReader and BufferedReader objects: “InputStreamReader read = new InputStreamReader(System.in);” “BufferedReader in = new BufferedReader(read);”. Finally, read a character: “char ch = (char)(in.read());”
2. Character-oriented functions
Note: The Character wrapper contains character data type. It also includes some functions to manipulate the character type data. One of its example is Character.isLetter(); which is used to check whether a given argument is a letter or not. It returns boolean type value either true or false .
3. Conversion from characters to ASCII code and vice versa
Note: Each character on computer is assigned a ASCII code. To obtain the ASCII code of a given character, -> Syntax: int variable l = (int) char variable2;
To convert ASCII code to character->Syntax: char variable! = (char) int variable2;
