Lesson 6: Characters and Strings in Java
Understanding character data type, Unicode, ASCII, and string manipulation in Java.
Character Data Type
Important: The character data type represents single characters.
Besides processing numeric values, Java can also process characters. The char data type is used to represent single characters. Character literals are enclosed in single quotes.
Example:
char letter = 'A';
char numChar = '4';
Important Distinction:
-
▶
String literals must be enclosed in double quotes (
" ") -
▶
Character literals are single characters enclosed in single quotes (
' ')
Thus, "A" is a string, while 'A' is a character.
Unicode and ASCII
Java supports Unicode — an encoding standard established by the Unicode Consortium to support the exchange, processing, and display of written texts in various world languages.
16-bit Unicode: Occupies two bytes, represented by four hexadecimal digits preceded by \u, from \u0000 to \uFFFF.
Examples: Greek letters α, β, γ are \u03b1, \u03b2, \u03b4 respectively.
ASCII Codes for Common Characters
| Characters | Decimal Codes | Unicode |
|---|---|---|
| '0' to '9' | 48 to 57 | \u0030 to \u0039 |
| 'A' to 'Z' | 65 to 90 | \u0041 to \u005A |
| 'a' to 'z' | 97 to 122 | \u0061 to \u007A |
Equivalent statements:
char letter = 'A';
char letter = '\u0041'; // Unicode for 'A' is 0041
// Both statements assign character 'A' to variable letter
Increment/Decrement with char: You can use increment and decrement operators with char variables.
char ch = 'a';
System.out.println(++ch); // Displays 'b'
Escape Sequences for Special Characters
| Escape Sequence | Name | Unicode | Decimal Value |
|---|---|---|---|
\b |
Backspace | \u0008 | 8 |
\t |
Tab | \u0009 | 9 |
\n |
New line | \u000A | 10 |
\\ |
Backslash | \u005C | 92 |
\" |
Double quotes | \u0022 | 34 |
Example with quotes:
System.out.println("He said: \"Let's go!\"");
// Output: He said: "Let's go!"
Example with backslash:
System.out.println("\\t is a tab character");
// Output: \t is a tab character
Character Comparison and Checking
Character comparison examples:
'a' < 'b' // true (97 < 98)
'a' < 'A' // false (97 > 65)
'1' < '8' // true (49 < 56)
Character Class Methods
| Method | Description |
|---|---|
Character.isDigit(ch) |
Returns true if ch is a digit |
Character.isLetter(ch) |
Returns true if ch is a letter |
Character.isLetterOrDigit(ch) |
Returns true if ch is a letter or digit |
Character.isLowerCase(ch) |
Returns true if ch is lowercase |
Character.isUpperCase(ch) |
Returns true if ch is uppercase |
Character.toLowerCase(ch) |
Returns lowercase of ch |
Character.toUpperCase(ch) |
Returns uppercase of ch |
Example using Character methods:
char ch = 'A';
if (Character.isUpperCase(ch)) {
System.out.println(ch + " is uppercase");
}
if (Character.isDigit(ch)) {
System.out.println(ch + " is a digit");
}
char lowerCh = Character.toLowerCase(ch); // 'a'
String Type - Part 1
Important: A string is a sequence of characters. The String class is used to represent strings in Java.
String declaration:
String message = "Welcome";
Basic String Methods
| Method | Description |
|---|---|
length() |
Returns number of characters in string |
charAt(index) |
Returns character at specified index |
concat(s1) |
Returns new string concatenated with s1 |
toUpperCase() |
Returns new string in uppercase |
toLowerCase() |
Returns new string in lowercase |
trim() |
Returns new string with whitespace trimmed |
Examples:
String message = "Welcome to Java";
int len = message.length(); // 15
char ch = message.charAt(0); // 'W'
String upper = message.toUpperCase(); // "WELCOME TO JAVA"
String lower = message.toLowerCase(); // "welcome to java"
String trimmed = " Hello ".trim(); // "Hello"
String concatenation:
String s1 = "Hello";
String s2 = "World";
String s3 = s1.concat(s2); // "HelloWorld"
String s4 = s1 + s2; // "HelloWorld" (using + operator)
String s5 = s1 + " " + s2; // "Hello World"
Reading Strings and Characters from Console
Reading strings using next():
Scanner input = new Scanner(System.in);
System.out.print("Enter three words: ");
String s1 = input.next(); // Reads until first whitespace
String s2 = input.next();
String s3 = input.next();
Reading entire line using nextLine():
System.out.print("Enter a line: ");
String line = input.nextLine(); // Reads entire line until Enter
Reading a character:
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0); // Get first character
Laboratory Work
Lab 1: Working with Strings
Objective: Create a program that prompts user to enter names of two cities and displays them in alphabetical order. Replace three dots (...) in the code with necessary code.
[File name and class name: L6Lab1.java]
Expected Output:
Enter name of first city:VoronezhEnter name of second city:MoscowCity names in alphabetical order: Moscow Voronezh
Algorithm:
- Create a new Java file named
L6Lab1.java. - Import the Scanner class for user input:
import java.util.Scanner; - Define the class
L6Lab1with a main method. - Step 1: Get names of two cities from user. Use
nextLine()method to read city names that may contain spaces:Scanner input = new Scanner(System.in); // Get names of two cities System.out.print("Enter name of first city: "); String city1 = ...; System.out.print("Enter name of second city: "); String city2 = ...; - Important: Using
nextLine()instead ofnext()allows reading city names that may contain multiple words separated by spaces. - Step 2: Compare the two city names using
compareTo()method and display them in alphabetical order:if (city1.compareTo(city2) < 0) { System.out.println("City names in alphabetical order: " + city1 + " " + city2); } else { System.out.println("City names in alphabetical order: " + ... + " " + ...); } - Important: The
compareTo()method returns:-
▶
Negative value if
city1is less thancity2(comes earlier in alphabetical order) -
▶
Zero if
city1equalscity2 -
▶
Positive value if
city1is greater thancity2(comes later in alphabetical order)
-
▶
Negative value if
- Close the Scanner object.
- Test the program with different city names (including multi-word names like "New York" or "St. Petersburg").
- Add the task description as a comment at the beginning of the program.
- Upload the file to the learning management system.
Independent Work Tasks
Task 1: Character Type Operations
Objective: Write a program to:
- ▶ Find and output ASCII codes corresponding to characters '1', 'A', 'B', 'a', and 'b'
- ▶ Find and output characters corresponding to decimal codes 40, 59, 79, 85, and 90
- ▶ Find and output characters corresponding to hexadecimal codes 40, 5A, 71, 72, and 7A
Expected Output:
ASCII code for '1' = 49 ASCII code for 'A' = 65 ASCII code for 'B' = 66 ASCII code for 'a' = 97 ASCII code for 'b' = 98 Character for decimal 40 = ( Character for decimal 59 = ; Character for decimal 79 = O Character for decimal 85 = U Character for decimal 90 = Z Character for hex 40 = @ Character for hex 5A = Z Character for hex 71 = q Character for hex 72 = r Character for hex 7A = z
Hint: Use type casting between char and int, and Unicode escape sequences for hexadecimal values.
[File name and class name: L6Task1.java]
Task 2: String Type Operations
Objective: Let s1 be " Welcome " and s2 be " welcome ". Write code for the following statements:
- Check if
s1equalss2and assign result to boolean variableisEqual - Compare
s1ands2and assign result to int variablex - Check if
s1has prefix "AAA" and assign result to boolean variableb - Assign length of
s1to int variablex - Assign first character of
s1to char variablex - Create new string
s3by concatenatings1ands2 - Create substring of
s1from index 1 to index 4 - Create new string
s3by convertings1to lowercase - Create new string
s3by trimming whitespace from both ends ofs1
Expected Output:
isEqual = false x = -32 b = false Length x = 9 First char x = ' ' s3 = " Welcome welcome " Substring = "Welc" Lowercase s3 = " welcome " Trimmed s3 = "Welcome"
Hint: Use string methods equals(), compareTo(), startsWith(), length(), charAt(), concat() or + operator, substring(), toLowerCase(), trim().
[File name and class name: L6Task2.java]
Task 3: Find Substring Between Characters
Objective: A character is entered (stored in variable c). There is a string s containing exactly two characters c. Find the substring between these two characters.
Expected Output:
Result for "astra" string and 'a' char is: str Result for "nana" string and 'a' char is: n
Hint: Use indexOf() method to find positions of the character, then substring() to extract text between them.
[File name and class name: L6Task3.java]
Task 4: Word Counter
Objective: Write a program that reads multiple words using next() and displays them in reverse order.
Expected Output:
Enter 5 words: one two three four five In reverse order: five four three two one
Hint: Use .next() method.
[File name and class name: L6Task4.java]
Task 5: Name Formatter
Objective: Create a program that formats a full name.
Expected Output:
Enter first name: Ivan Enter last name: Bikov Result: Full name: Ivan Bikov Uppercase: IVAN BIKOV Initials: I.B. Last, First: Bikov, Ivan
Hint: Use toUpperCase() and charAt(0) methods.
[File name and class name: L6Task5.java]
Task 6: Find Substring Between Characters
Objective: A character is entered (stored in variable c). There is a string s containing exactly two characters c. Find the substring between these two characters.
Expected Output:
Result for "astra" string and 'a' char is: str Result for "nana" string and 'a' char is: n
Hint: Use indexOf() method to find positions of the character, then substring() to extract text between them.
[File name and class name: L6Task6.java]