In Java, the Character
class is the wrapper class for the char
primitive data type. The Character
class provides a range of methods to work with char
values, including:
isDigit(char ch)
: Returnstrue
if the specifiedchar
value is a digit.isLetter(char ch)
: Returnstrue
if the specifiedchar
value is a letter.isWhitespace(char ch)
: Returnstrue
if the specifiedchar
value is a whitespace character.toLowerCase(char ch)
: Returns the lowercase equivalent of the specifiedchar
value.toUpperCase(char ch)
: Returns the uppercase equivalent of the specifiedchar
value.valueOf(char ch)
: Returns aCharacter
instance representing the specifiedchar
value.compareTo(Character anotherChar)
: Compares thisCharacter
instance with anotherCharacter
instance.equals(Object obj)
: Returnstrue
if the specified object is equal to thisCharacter
instance.
The Character
class also provides constants for commonly used char
values, such as Character.MAX_VALUE
and Character.MIN_VALUE
.
The Character
class is commonly used in applications that deal with text and character data. For example, it can be used to check whether a given character is a digit or a letter, or to convert a character to its lowercase or uppercase equivalent.
Here's an example Java program that demonstrates the use of some methods of the Character
class:
In this program, we first declare apublic class CharacterExample {
public static void main(String[] args) {
char ch = 'A';
// Check if the character is a letter
if (Character.isLetter(ch)) {
System.out.println(ch + " is a letter");
}
// Convert the character to lowercase
char lowercase = Character.toLowerCase(ch);
System.out.println("Lowercase of " + ch + " is " + lowercase);
// Convert the character to uppercase
char uppercase = Character.toUpperCase(ch);
System.out.println("Uppercase of " + ch + " is " + uppercase);
}
}
char
variable ch
and initialize it with the character 'A'
. We then use the isLetter
method of the Character
class to check whether ch
is a letter, and print a message accordingly.Next, we use the toLowerCase
method of the Character
class to convert ch
to its lowercase equivalent, and print the result. Similarly, we use the toUpperCase
method of the Character
class to convert ch
to its uppercase equivalent, and print the result.
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.