class Character

Introduction

The java.lang.Character class includes many useful static methods with which text (or characters) can be manipulated. The other text manipulating classes are String, StringBuffer, StringTokenizer and StringBuilder.

The Character class is a wrapper class for char data type. That is, a Character object represents char as an object; it gives an object form to a simple data type char.

The static methods of Character class are useful

  1. To know the character type like whether the character is of lowercase or uppercase, or digit etc.
  2. To convert the character from lowercase to uppercase etc.

Following is the class signature as defined in Java API.

public final class Character extends Object implements Serializable, Comparable

As you can observe, the Character class is final. It cannot be extended (like Math and String etc).

Following program illustrates the usage of some methods of class Character.
public class CharacterMethods
{
   public static void main(String args[])
    {					// Using Character objects to know equal or not
       Character xchar = new Character('x');
       Character xchar1 = new Character('x');
       Character ychar = new Character('y');
				// to get back char data type from Character object
       char c1 = xchar.charValue();    
       System.out.println("xchar value: " + c1);        		// prints x
       System.out.println("xchar and xchar1 same or not: " + xchar.compareTo(xchar1));    // prints 0
       System.out.println("xchar and ychar same or not: " + xchar.compareTo(ychar));  	// prints -1
       System.out.println("xchar and ychar same or not: " + xchar.equals(ychar)); // prints false
				     // to find a character can be a Java identifier
       char c2 = 'P';
       char c3 = '8';
       System.out.println("P suits as a starting letter of a Java identifier: " + Character.isJavaIdentifierStart(c2)); // true
       System.out.println("8 suits as a starting letter of a Java identifier: " + Character.isJavaIdentifierStart(c3));  // false
       System.out.println("8 can be placed anywhere except starting letter of Java identifier: " + Character.isJavaIdentifierPart(c3));   // true
						          // to know the properties of a character           
       System.out.println("is defined: " + Character.isDefined(c2));     		// true
       System.out.println("is digit: " + Character.isDigit(c2));    			// false
       System.out.println("is letter (alphabet): " + Character.isLetter(c2));   	// true
       System.out.println( "is letter or digit: " + Character.isLetterOrDigit(c2));  // true
       System.out.println( "is lower case: " + Character.isLowerCase(c2));     	// false
       System.out.println( "is upper case: " + Character.isUpperCase(c2));  	// true
       System.out.println( "to lower case: " + Character.toLowerCase(c2));   	// prints p
       System.out.println( "is space: " + Character.isWhitespace(c2));   	// false
    }
}


class Character
Output screenshot on different methods of class Character

charValue() method returns the char stored in xchar object. compareTo() method returns an integer value of zero if both Character objects represent the same character, else non-zero value is returned. equals() method also compares two characters, but it returns a boolean value and is useful in control structures.

isJavaIdentifierStart(c2) checks whether P is suitable as Java identifier starting character. isJavaIdentifierPart(c3) checks whether the digit 8 is suitable to be placed anywhere in the identifier except as the starting character. isDefined(c2) returns true as P is defined in Java Unicode. toUpperCase() and toLowerCase() methods convert the character to uppercase from lowercase or vice versa. Other methods are self explanatory. Always in Java, the isXXX() methods return a boolean value.

The following program validates a password for non-presence of digits.

public class PasswordValidation
{
   public static void main(String args[])
   {
       String password = "nagesh32rao"; 			
       boolean b = true;
       for(int i = 0; i < password.length(); i++)
       {
           if(Character.isDigit(password.charAt(i)) == true)
           { 	
 	     System.out.println( "Password is invalid");
	     b = false;
	     break;
           }
       }
       if(b == true)
       {
          System.out.println("Password is valid");
       }
    }
}

class Character

The password can be taken from keyboard or from command-line argument (it is taken directly to make the program simple). charAt() method of String class returns the character at the specified index (passed as parameter) in the string. isDigit() method checks the character is a digit or not.

File Analysis - Count

Let us write another program to practice the Character class methods. It is to count the number of uppercase letters, lowercase letters and digits present in a file and also to print all the uppercase letters.

Contents of text file Bench.txt

1. Do not waste time while you are on bench.
2. Learn new tools and new concepts.
3. Later, you may not get time to do the same.

The following program reads the above contents and prints the statistics.

import java.io.*;
public class FileStatistics
{
   public static void main(String args[]) throws IOException
   {
      FileReader fr = new FileReader("Bench.txt");

      int temp, lowerCount = 0, upperCount = 0, digitCount = 0;
      StringBuffer buffer1 = new StringBuffer();

       while((temp = fr.read() ) != -1)
       {
          char c1 = (char)temp;
          if(Character.isUpperCase(c1))
          {
            upperCount++;
            buffer1.append(c1 + " ");
          }
          else if(Character.isLowerCase(c1))
          {
            lowerCount++;
          }
          else if(Character.isDigit(c1))
          {
            digitCount++;
          }
      }
      System.out.println("Uppercase letters are: " + buffer1);
      System.out.println("No. of Uppercase letters: " + upperCount);
      System.out.println("No. of Lowercase letters: " + lowerCount);
      System.out.println("No. of Digits: " + digitCount);      
      fr.close();
   }
}

class Character

The program requires the understanding of file copying using FileReader. The read() of FileReader reads each character in the file and returns it as an integer value.

char c1 = (char) temp;

The int data type returned by the read() method is converted back into character to be used in the code.

isLowerCase(c1) and isUpperCase(c1) checks whether the character c1 is lowercase or uppercase.

StringBuffer buffer1 = new StringBuffer();
buffer1.append(c1 + " ");

To store the uppercase letters temporarily, a StringBuffer object buffer1 is created. append() method of StringBuffer is used to add all the uppercase letters to preserve.

Leave a Comment

Your email address will not be published.