Character Class


Normally, when we work with characters, we use the primitive data type char:

1char ch = 'a';
2 
3// Unicode for uppercase Greek omega character
4char uniChar = '\u039A';
5 
6// An array of chars
7char charArray[ ] = { 'a', 'b', 'c', 'd', 'e' };

In development, we sometimes come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class java.lang.Character for the data type char. The class offers a number of useful class (i.e., static) methods for manipulating characters. The following script creates two Character objects: (i) one using the Character constructor and (ii) another one using the autoboxing explained in the next slide:

1Character ch1 = new Character('a');
2Character ch2 = 'a';

MyChar.java (java.lang.Character class)

 public class MyChar {
   public static void main( String[ ] args ) {
     char      a[ ] = { 'H', 'e', 'l', 'l', 'o' };
     Character b[ ] = { 'H', 'e', 'l', 'l', 'o' };
     String       c = "Hello";

     System.out.println( a.toString( ).equals( c ) );
       //  true   false   error
     System.out.println( b.toString( ).equals( c ) );
       //  true   false   error
     System.out.println( c.equals( a ) );        
       //  true   false   error
     System.out.println( c.equals( b ) );   
       //  true   false   error
     System.out.println( a[0] == b[0] );          
       //  true   false   error
     System.out.println( b[0] == 'H'  );          
       //  true   false   error
     System.out.println( a == b );               
       //  true   false   error
   }
 }