Lesson - 1 - Characters

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

DATATYPES AND CONTROL STRUCTURES:

Using Characters in Java

A character in Java is represented by a single digit in a string. A string is identified by the use of double
quotes whereas a character is identified by single quotes. The cool thing about characters is that we can
represent them as numbers. The value of each character can be found from the ASCII table.
(http://www.asciitable.com).

If you look at the ASCII table, the letters:


• A – Z have the decimal values 65 – 90
• a – z have the decimal values 97 – 122

Java allows us to convert these numbers to characters.

You may have noticed that with Scanner, there is no nextChar() method. To read in a
character, we are forced to read in a string and then check for the first position of the string.
If we wanted to check character by character, we would need to read in a string, and then
set up a loop to step through each character in the string. We will let the note on Strings deal
with this. For now, note that we can convert between characters and numbers.

In the following program, we will ask the user for a number and then convert it a letter.

public class ConvertChar {

public static void main (String[] args)


{
Scanner scan = new Scanner(System.in);

int num;

System.out.print(“Enter a number (65 – 90) OR (97 – 122): \t” );


num = scan.nextInt();

System.out.print(“\n\nYour value of ” + num + “ is the letter \””


+ (char)num + “\””);
}
}

The output would look like:

Enter a number (65 – 90) OR (97 – 122): 67

Your value of 68 is the letter C

Using Characters in Java Page 1 of 5


You will notice in the above program, we simply cast the number to a char. We could have also made a
variable to store the character by modifying the above program:

public class ConvertChar {

public static void main (String[] args)


{
Scanner scan = new Scanner(System.in);

int num;
char letter;

System.out.print(“Enter a number (65 – 90) OR (97 – 122): \t” );


num = scan.nextInt();

letter = (char)num;

System.out.print(“\n\nYour value of ” + num + “ is the letter \””


+ letter + “\””);
}
}

You can even use letter++; to increase the value of the character to the next one that appears in
the ASCII table. However, we need to be a little bit careful:

char letter = ‘a’;


letter++; ‘a’ ‘b’
This is not the same as:

char letter = ‘a’;


letter = letter + 1;

The reason why the first scenario works and not the second is because the first scenario, Java
understands to that the letter is a number and we want to move one letter down in the alphabet. In the
second scenario, even though letter++ is the same as letter = letter + 1, Java see this as an equation
rather than a transformation, and this cannot distinguish that we want to change the decimal value of the
variable letter. Java sees this as a calculation and determines a type mismatch, trying to add an integer
to the character in the variable letter.

THE CHARACTER CLASS:


The Character class offers a number of useful methods for manipulating
characters that are not available in the String class. For example, you can
use the Character class to determine if a character is uppercase, lowercase, a
number, etc.). Although we can do this in the String class, it might be easier
to implement this in the Character class.

Using Characters in Java Page 2 of 5


You can create a Character object from a char value. For example, the following statement creates a
Character object for the character ‘x’:

Character myChar = new Character(‘x’);

The following are some of the methods included in the Character class that allow you to do various
things with characters:

METHOD DESCRIPTION EXAMPLE

charValue (): char Returns the char value. myChar.charValue();

compareTo(Character Compares this character with another character. myChar.compareTo(new


anotherChar): int Returns the value 0 if the two characters are Character(‘a’));
equal, or a value less than 0 if they are not
equal.

equals(Character anotherChar): Compares this character with another character. myChar.equals(new


boolean Returns true if the two characters being Character(‘a’));
compared are equals; otherwise returns false.

Character.isWhiteSpace(char c): Determines if the specified character is white Character.isWhiteSpace(‘x’);


boolean space.

Character.isDigit(char c): boolean Determines if the specified character is a digit. Character.isDigit(‘x’);


Returns true if it is a digit; otherwise returns
false.
Character.isLetter(char c): boolean Determines if the specified character is a letter. Character.isLetter(‘x’);
Returns true if it is a letter; otherwise returns
false.
Character.isLetterOrDigit(char c): Determines if the specified character is a letter Character.isLetterOrDigit(‘x’);
boolean or a digit. Returns true if it is a letter or a digit;
otherwise returns false.

Character.isLowerCase(char c): Determines if the specified character is Character.isLowerCase(‘x’);


boolean lowercase. Returns true if it is lowercase;
otherwise returns false.
Character.isUpperCase(char c): Determines if the specified character is Character.isUpperCase(‘x’);
boolean uppercase. Returns true if it is uppercase;
otherwise returns false.

Character.toLowerCase(char c): Converts the character to lowercase. Character.toLowerCase(‘x’);


char
Character.toUpperCase(char c): Converts the character to uppercase. Character.toUpperCase(‘x’);
char

toString(): String Converts a Character object to a String object. myChar.toString();

You can find the rest of the Character class methods by referring to the Java API documentation.

We will not focus too much on the Character Class in the course, but there might be times when you
want to utilize the methods from here in a program.

CHARACTER + STRING CLASS SAMPLE PROGRAM


The following program will demonstrate how to combine the Character class methods with the String
class methods to determine if the characters in the string the user enters are upper case characters,
lower case characters, or a number.

Using Characters in Java Page 3 of 5


import java.util.Scanner;

public class PostalCode {

public static void main(String[] args)


{
Scanner scan = new Scanner (System.in);

String code;

System.out.print("Type a postal code: ");


code = scan.nextLine();

System.out.println();

for (int i = 0; i < code.length(); i++)


{
if (Character.isUpperCase(code.charAt(i)))
{
System.out.println("UPPERCASE");
}
else if (Character.isLowerCase(code.charAt(i)))
{
System.out.println("LOWERCASE");

}
else
{
System.out.println("NUMBER");
}
}
}
}

The output will look like:

Notice that in this output, the postal code is only 6 digits, yet we got 7 output messages. This is because
in using the character class, Java counted the space as a digit. We could extend this code to check for
whitespace by implementing the isWhitespace() method from the Character class. In our example, we
will just add a space in the output:

Using Characters in Java Page 4 of 5


import java.util.Scanner;

public class PostalCode {

public static void main(String[] args) {


Scanner scan = new Scanner (System.in);

String code;

System.out.print("Type a postal code: ");


code = scan.nextLine();

System.out.println();

for (int i = 0; i < code.length(); i++)


{
if (Character.isUpperCase(code.charAt(i)))
{
System.out.println("UPPERCASE");
}
else if (Character.isLowerCase(code.charAt(i)))
{
System.out.println("LOWERCASE");
}
else if (Character.isWhitespace(code.charAt(i)))
{
System.out.println();
}
else
{
System.out.println("NUMBER");
}
}
}
}

The output now looks like:

Using Characters in Java Page 5 of 5

You might also like