VisualStudioTutor.com Java Tutorial All Lessons

Lesson 12 of 20

Strings and Text Processing

Compare, search, split, format, and transform text using Java's String class.

Learning objectives

  • Create and concatenate strings.
  • Compare string contents correctly with equals.
  • Use common methods such as length, substring, contains, and replace.
  • Split text into parts.
  • Use StringBuilder for repeated modifications.

1. Strings are objects

String is a class, not a primitive type. A string contains a sequence of characters.

Example: basic string methods

String course = "Java Programming";

System.out.println(course.length());
System.out.println(course.toUpperCase());
System.out.println(course.contains("Java"));
System.out.println(course.substring(0, 4));

2. Compare contents with equals

Use equals when you want to compare the text stored in two strings. == compares object references and should not be used for normal content comparison.

Example: password check

String entered = "java123";
String expected = "java123";

if (entered.equals(expected)) {
    System.out.println("Password matched.");
}

3. Splitting text

String record = "S001,Amina,Computer Science";
String[] parts = record.split(",");

System.out.println("ID: " + parts[0]);
System.out.println("Name: " + parts[1]);
System.out.println("Course: " + parts[2]);

4. StringBuilder

Strings are immutable: methods that appear to modify a string actually produce another string. When text is changed repeatedly, StringBuilder can be more appropriate.

StringBuilder report = new StringBuilder();
report.append("Student Report
");
report.append("--------------
");
report.append("Name: Amina
");
report.append("Mark: 88
");

System.out.println(report);

Mini project: username generator

public class UsernameGenerator {
    public static void main(String[] args) {
        String fullName = "Nur Aisyah Rahman";

        String normalized = fullName.trim().toLowerCase();
        String[] words = normalized.split("\s+");

        String firstName = words[0];
        String lastName = words[words.length - 1];

        String username = firstName.charAt(0) + lastName;

        System.out.println("Name: " + fullName);
        System.out.println("Username: " + username);
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
Using == for text comparisonIt compares references rather than normal string content.Use equals or equalsIgnoreCase.
Substring index errorThe requested index is outside the string.Check length() and remember the end index is exclusive.
Unexpected backslash behaviorBackslash begins an escape sequence.Use \ for a literal backslash inside a Java string.

Summary

You can now perform common text operations safely. Lesson 13 introduces methods, allowing you to package reusable logic into named operations.