Skip to content

Programming by Design

If you're not prepared to be wrong, you'll never come up with anything original. – Sir Ken Robinson

  • About
  • Java-PbD
  • C-PbD
  • ASM-PbD
  • Algorithms
  • Other

What if we didn’t have Character?

Posted on March 13, 2017March 14, 2020 By William Jojo
Code

Consider what things would be like without the wrapper classes. How could we classify chars? For instance, alphabetic, numeric, alphanumeric. Or how could you convert between case?

CharEx.java
public class CharEx {
  
  public static void main(String[] args) {
    
    char c;
    
    c = 'a';
    
    System.out.println(c);
    
    if ( c >= '0' && c <= '9' )
      System.out.println (c + " is a digit.");
    
    if ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') )
      System.out.println (c + " is a letter.");
    
  }
  
}

Now let's translate this into methods! We will create our own MyCharacter (to avoid collisions) and we will go one step further and add my as a prefix for the method names as well.

MyCharacter.java
public class MyCharacter {
  
  public static boolean isDigit(char c) {
    
    return ( c >= '0' && c <= '9' );
    
  }
  
  public static boolean isLetter(char c) {
    
    return ( (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') );
  
  }

  static boolean isLetterOrDigit(char c) {

    return isLetter(c) || isDigit(c);

  }
  
  static char toUpperCase(char c) {

    //... convert
    return 0;

  }
  
  static char toLowerCase(char c) {

    //... convert
    return 0;

  }
}

You may be thinking to yourself, why does the return statement look like that? Good question. We could have written:

if ( c >= '0' && c <= '9' )
  return true;
else
  return false;

But honestly, the expression already evaluates to boolean (true or false). So, we just return the evaluation.

Finally, here is an exerciser program to test the class:

Exerciser.java
import java.util.*;

public class Exerciser {
  
  static Scanner kb = new Scanner(System.in);
  
  public static void main(String[] args) {
    
    char c;
    
    System.out.print("Enter a character: ");
    while ( kb.hasNext() ) {
      
      c = kb.next().charAt(0);
      
      if (MyCharacter.isDigit(c))
        System.out.println(c + " is a digit!");
      
      if (MyCharacter.isLetter(c))
        System.out.println(c + " is a letter!");
      
      System.out.print("Enter a character: ");
    }
  }
}

For you TO-DO: How would you complete the toUpperCase() and toLowerCase() methods?

Post navigation

❮ Previous Post: Network Details for CISS-150
Next Post: Java Boilerplate ❯

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright © 2018 – 2025 Programming by Design.