Character in Java
The Character class is a wrapper class that wraps the primitive char data type and provides a Character object. A Character object contains a single field of char. This Character class also provides a number of useful class methods (static methods) for manipulating characters. The Character class is immutable, which means once it is created, it cannot be changed.
Character object can be created with the Character constructor.
Example
package com.example;
public class CharacterExample {
public static void main(String[] args) {
Character ch = new Character('a');
System.out.println(ch);
}
}
Output
Character Autoboxing/Unboxing
The Java compiler creates a Character object, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing.
Character Class Methods
Following are the lists of some of the useful methods in the Character class which must be accessed in a static way:
Charater Class Method | Description |
---|---|
public static isLetter(char ch) | Determines if the specified char value is a letter. |
public static boolean isDigit(char ch) | Determines if the specified char value is a digit. |
public static boolean isUpperCase(char ch) | Determines if the specified char value is uppercase. |
public static boolean isLowerCase(char ch) | Determines if the specified char value is lowercase. |
public static char toUpperCase(char ch) | Returns the specified char value in uppercase form. |
public static char toLowerCase(char ch) | Returns the specified char value in lowercase form. |
public static toString(char ch) | Returns the specified character value in a String object — that is, a one-character string. |
public static boolean isWhitespace(char ch) | Determines if the specified char value is white space. |
Example
package com.example;
public class CharacterExample {
public static void main(String[] args) {
char c1 = 'a';
boolean valueIsUpperCase = Character.isUpperCase(c1);
boolean valueIsDigit = Character.isDigit(c1);
String stringValue = Character.toString(c1);
System.out.println("Is value uppercase : " + valueIsUpperCase);
System.out.println("Is value digit : " + valueIsDigit);
System.out.println("Character to String value : " + stringValue);
}
}
Output
Is value digit : false
Character to String value : a