Character Class


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

 char ch = 'a';

 // Unicode for uppercase Greek omega character
 char uniChar = '\u039A';

 // An array of chars
 char 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:

 Character ch1 = new Character('a');
 Character 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
   }
 }
   




      Barking dogs seldom bite.