Unit 03 · lesson
Strings Are Objects, and Text Has Structure
Text processing is more than printing a sentence. Usernames, commands, file records, labels, messages, and identifiers all have structure.
Java represents text with the String class.
void main() {
String status = " READY ";
IO.println(status.length());
IO.println(status.trim());
IO.println(status.toLowerCase());
}
These operations produce information or new strings. They do not mutate the original string object in place.
Strings are immutable
Consider:
String name = "java";
name.toUpperCase();
IO.println(name);
The output remains java because toUpperCase() returns a new String. The variable was not reassigned.
To keep the transformed value:
name = name.toUpperCase();
Now name refers to the new string value.
This is your first encounter with immutability. Later, records and other object designs will use the same idea intentionally.
Content equality is not reference identity
For text, use .equals(...) when you need to compare content.
String command = IO.readln("Command: ");
if (command.equals("start")) {
IO.println("starting");
}
Do not build the habit of using == for String content.
== on object references asks whether both references identify the same object. .equals(...) is the content/value equality contract used by String.
We will revisit this when objects and collections make reference identity more visible.
Normalize only when the requirement says to
A command parser may intentionally ignore extra outer whitespace and capitalization:
String command = IO.readln("Command: ").trim().toLowerCase();
Then START becomes start.
But normalization is a design decision. A password, case-sensitive identifier, legal name, or data record may have different rules. Never clean data merely because it makes your code easier.
Extract structure
Suppose a supplied record has this format:
MTHS-2180-AUTO
Useful String methods include:
record.length()
record.contains("-")
record.indexOf("-")
record.substring(...)
record.split("-")
Try:
void main() {
String record = "MTHS-2180-AUTO";
String[] parts = record.split("-");
IO.println(parts[0]);
IO.println(parts[1]);
IO.println(parts[2]);
}
You do not need to master arrays yet. For now, notice that one text record can be transformed into multiple structured pieces.
String evidence lab
Start with these raw values:
" START "
"mths-2180-auto"
"ERROR: sensor timeout"
" "
For each, choose operations that answer a specific question:
- Is it blank after trimming?
- Does it contain a known prefix?
- Should case be normalized?
- How many fields can be extracted?
Record the question first, then the method you selected. That prevents the lab from becoming a tour of random String methods.
What matters
A String method is useful because it supports a data rule. Your job is to connect:
requirement -> text structure -> operation -> evidence
That pattern will return when we parse files and validate capstone inputs.