Skip to main content
EDU-MMCS
You are currently using guest access (Log in)

Java Programming Language (Eng)

  1. Home
  2. Courses
  3. Весенний семестр
  4. Java Eng
  5. Basic Programming Language Constructs
  6. Lesson #6: Characters and Strings in Java

Lesson #6: Characters and Strings in Java

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:
Voronezh
Enter name of second city:
Moscow
City names in alphabetical order: Moscow Voronezh

                        

Algorithm:

  1. Create a new Java file named L6Lab1.java.
  2. Import the Scanner class for user input:
    
    import java.util.Scanner;
  3. Define the class L6Lab1 with a main method.
  4. 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 = ...;
  5. Important: Using nextLine() instead of next() allows reading city names that may contain multiple words separated by spaces.
  6. 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: " + 
            ... + " " + ...);
    }
  7. Important: The compareTo() method returns:
    • ▶ Negative value if city1 is less than city2 (comes earlier in alphabetical order)
    • ▶ Zero if city1 equals city2
    • ▶ Positive value if city1 is greater than city2 (comes later in alphabetical order)
  8. Close the Scanner object.
  9. Test the program with different city names (including multi-word names like "New York" or "St. Petersburg").
  10. Add the task description as a comment at the beginning of the program.
  11. 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:

  1. Check if s1 equals s2 and assign result to boolean variable isEqual
  2. Compare s1 and s2 and assign result to int variable x
  3. Check if s1 has prefix "AAA" and assign result to boolean variable b
  4. Assign length of s1 to int variable x
  5. Assign first character of s1 to char variable x
  6. Create new string s3 by concatenating s1 and s2
  7. Create substring of s1 from index 1 to index 4
  8. Create new string s3 by converting s1 to lowercase
  9. Create new string s3 by trimming whitespace from both ends of s1

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]

© 2023 Java Programming Educational Material. Lesson 6: Characters and Strings in Java.

Mastering character data type, Unicode, ASCII, escape sequences, and string manipulation in Java.

◄ Lesson #5: Mathematical Functions in Java
Lesson # 7: For and Foreach ►
Skip Navigation
Navigation
  • Home

    • Site pages

      • My courses

      • Tags

    • My courses

    • Courses

      • Весенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

        • МО_4курс

        • KP

        • АБМ1_ИИБ_25-26

        • Java Eng

          • Lesson 0. Introduction

          • Basic Programming Language Constructs

            • AssignmentLesson 1. Programming on Java in Microsoft Visual ...

            • AssignmentLesson 2. Data Types and Type Casting. Boolean type

            • AssignmentLesson 3. Java Conditional statement IF

            • AssignmentLesson 4: Ternary Operator and Switch Statement

            • AssignmentLesson #5: Mathematical Functions in Java

            • AssignmentLesson #6: Characters and Strings in Java

            • AssignmentLesson # 7: For and Foreach

          • Methods (functions)

          • Arrays

          • Topic 5

          • Topic 6

          • Topic 7

          • Topic 8

          • Topic 9

          • Topic 10

          • Topic 11

          • Topic 12

          • Topic 13

          • Topic 14

          • Topic 15

          • Topic 16

        • МО (ПО)

      • Осенний семестр

        • Прикладная математика и информатика

        • Фундаментальная информатика и ИТ

        • Математика, механика

        • Педагогическое образование

        • Магистратура

          • Разработка мобильных приложений и компьютерных игр

        • Аспирантура

        • Вечернее отделение

        • Другое

      • Воскресная компьютерная школа

        • Пользователь компьютера плюс

        • Пользователь прикладных программ

        • Программирование I ступень

        • Программирование II ступень

        • Программирование III ступень

        • Архив

      • Воскресная математическая школа

        • Открытое тестирование РНОМЦ и мехмата ЮФУ - 2025

        • Олимпиадная математическая школа

        • Повышение квалификации

        • Доступная математика

        • Лаборатория математического онлайн-образования мех...

        • Осенняя универсиада

        • Научно-практическая конференция

        • ВМШ

          • ВМШ -2025

        • Летняя олимпиадная математическая школа РНОМЦ и ме...

      • Государственная итоговая аттестация

      • Дополнительное образование

      • Олимпиады

      • Видеолекции

      • Разное

      • Архив курсов

      • Заочная школа мехмата ЮФУ

You are currently using guest access (Log in)
Java Eng
Data retention summary
Get the mobile app Яндекс.Метрика