Character Class
The Character class in Java is a wrapper class that provides a number of useful methods for working with characters. The char primitive type in Java can only represent a single Unicode character, while the Character class provides a set of static methods for working with Unicode characters and converting between char values and String objects.
Example of using the Java Character class:
public class CharacterExample {
public static void main(String[] args) {
char c1 = 'a';
char c2 = '1';
// Check if the character is a letter
boolean isLetter = Character.isLetter(c1);
System.out.println(c1 + " is a letter: " + isLetter);
// Check if the character is a digit
boolean isDigit = Character.isDigit(c2);
System.out.println(c2 + " is a digit: " + isDigit);
// Convert the character to uppercase
char upper = Character.toUpperCase(c1);
System.out.println("Uppercase of " + c1 + " is " + upper);
// Convert the character to lowercase
char lower = Character.toLowerCase(c2);
System.out.println("Lowercase of " + c2 + " is " + lower);
}
}Source:www.theitroad.comIn this example, we use the Character class to perform some common character operations.
Here are some of the most commonly used methods in the Character class:
isLetter(char c): Returns true if the specified character is a letter.isDigit(char c): Returns true if the specified character is a digit.isWhitespace(char c): Returns true if the specified character is whitespace (space, tab, newline, carriage return, or form feed).toUpperCase(char c): Converts the specified character to upper case.toLowerCase(char c): Converts the specified character to lower case.valueOf(char c): Returns aCharacterobject representing the specifiedcharvalue.toString(char c): Returns aStringobject representing the specifiedcharvalue.
Here's an example of using some of these methods:
char ch = 'A'; System.out.println(Character.isLetter(ch)); // Output: true System.out.println(Character.isDigit(ch)); // Output: false System.out.println(Character.toUpperCase(ch)); // Output: 'A' System.out.println(Character.valueOf(ch)); // Output: 'A' System.out.println(Character.toString(ch)); // Output: "A"
In addition to these methods, the Character class also provides methods for comparing characters, testing for Unicode category membership, and working with character sets and encodings.
