Lesson - 1 - Characters
Lesson - 1 - Characters
Lesson - 1 - Characters
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).
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.
int num;
int num;
char letter;
letter = (char)num;
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:
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 following are some of the methods included in the Character class that allow you to do various
things with characters:
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.
String code;
System.out.println();
}
else
{
System.out.println("NUMBER");
}
}
}
}
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:
String code;
System.out.println();