All textual information on the computer is represented as sequences of characters. In this module, we look more closely into the details of using and storing textual data in terms of variables of type characters and strings.
Characters
Characters are the singular atomic units that represent textual information. This section presents fundamental information about how characters are represented and used in Java.
Exercise
Write a program that checks if a given character is lowercase or uppercase. You may assume the user can only input one character.
Solution
In order to solve this problem, we can simply make use of the ASCII encoding hierarchy, where all lowercase letters are encoded in the sorted fashion in the same closed range of numbers and similarly the uppercase letters follow the same encoding style. Therefore, by checking if the numeric encoding of the character is within the given ranges, one can determine whether a character is a lowercase letter or not.
Strings
Text can generally be represented using String type in Java. Here we introduce what are String types, their syntax and usage for processing and storing textual information.
Exercise
Write a Java program where the program reads two names and sorts them in the alphabetical order. You may assume that the user only inputs two uppercase strings, and the output is the ordered list of strings.
Solution
In this exercise, we will make use of the built-in functionalities of the String class which allows comparing two text segments lexicographically and return the comparison outcome in terms of an integer. Please check out the solution below as an example of how built-in methods can be invoked through String type objects, representing textual segments.
Data Types in Java
We have so far introduced the primary ways information can be declared and used in Java in terms of different types of variables or classes. In this section, we review the general approaches to data representation in Java and how information can be transferred into different formats using data type conversion methods.
More information on primitive data types in Java can be seen following Oracle’s online tutorial available on this link. The Oracle website also includes documentation about Wrapper classes, distributed as part of the lang package. Please follow the links below to see the descriptions of each class:
- Byte class
- Short class
- Integer class
- Long class
- Float class
- Double class
- Character class
- String class
Please follow the instructions to the self-assessment quiz and revise the new concepts.