Details of the Java Character class

  • 2020-07-21 07:38:13
  • OfStack

When using characters, we usually use the built-in data type char.

The instance


char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u039A'; 
//  A character array 
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; 

However, in real development, we often come across situations where we need to use objects instead of built-in data types. To solve this problem, the Java language provides the wrapper Character class for the built-in data type char.

The Character class provides a series of methods to manipulate characters. You can create an Character class object using Character's constructor, for example:

Character ch = new Character('a');

In some cases, the Java compiler automatically creates 1 Character object.

For example, if one argument of type char is passed to a method that requires one argument of type Character, the compiler automatically converts the argument of type char to an OBJECT of type Character. This feature is called packing, which in turn is called unpacking.

The instance


// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';

// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');

Escape sequences

Characters preceded by backslashes (\) represent escape characters that have special meaning to the compiler.

The following list shows the escape sequence of Java:

转义序列  描述
\t  在文中该处插入1个tab键
\b  在文中该处插入1个后退键
\n  在文中该处换行
\r 在文中该处插入回车
\f 在文中该处插入换页符
\'  在文中该处插入单引号
\" 在文中该处插入双引号
\\ 在文中该处插入反斜杠

The instance

When a print statement encounters an escape sequence, the compiler interprets it correctly.


public class Test {
  public static void main(String args[]) {
   System.out.println("She said \"Hello!\" to me.");
  }
}

The compilation and operation results of the above instances are as follows:

She said "Hello!" to me.

Character method

Here are the methods of the Character class:

序号 方法与描述
1

isLetter()

是否是1个字母

2

isDigit()

是否是1个数字字符

3

isWhitespace()

是否1个空格

4

isUpperCase()

是否是大写字母

5

isLowerCase()

是否是小写字母

6

toUpperCase()

指定字母的大写形式

7

toLowerCase()

指定字母的小写形式

8

toString()

返回字符的字符串形式,字符串的长度仅为1

I hope you found this article helpful


Related articles: