Explain it simply
Explain it simply
A String is like a string of beads, with characters threaded in order. Each bead has a number starting at 0, so in "Java" the J is at 0 and the first a is at 1. Usernames, emails, search keywords, messages and titles in an app are all Strings.
There is one important rule: the bead string itself cannot be changed. Calling a method like toUpperCase() hands you a brand-new string in capitals and leaves the original as it was. You only keep the change if you store the result in a variable.
Problem → Why → Solution
The problem: the right password is rejected
The login check worked when it was tested with literals. But when the text comes from real input, the correct password prints "Wrong password". A second bug hides on the line above: the username looks lowercased, but it is not.
public class Main {
public static void main(String[] args) {
String saved = "secret";
String typed = "sec";
typed = typed + "ret"; // built at runtime, like real input
String user = " Aye ";
user.strip().toLowerCase(); // result thrown away
System.out.println("[" + user + "]"); // still " Aye "
if (typed == saved) { // compares references, not text
System.out.println("Welcome");
} else {
System.out.println("Wrong password");
}
}
}Why does this happen?
A String is an object, so == only asks "do these two variables point to the same object in memory?". A string concatenated at runtime is a new object, so the answer is false even when the text matches. To compare text you need equals(). As for the strip() line, Strings are immutable, so nothing changes unless you assign the result back with user = ....
Core concept: an immutable object with indexes
In Java, String is a class, not a primitive type, which is why it is written with a capital S and has methods. Characters are indexed from 0, so for "Java Tutorial" length() is 13 and the last index is 12. charAt(i) gives the character at one index, and an index outside the range throws a StringIndexOutOfBoundsException. For a String, length() is a method with parentheses; the array length you will meet in a later lesson is a field without them.
Strings are immutable: once created, they cannot be changed. Every method such as toUpperCase(), strip(), replace() and substring() returns a new String. That is why you can chain calls: email.strip().toLowerCase(). indexOf("@") returns the index of the first match, or -1 if there is none. substring(begin, end) cuts from begin up to but not including end, and substring(begin) runs to the end.
strip() removes leading and trailing whitespace. trim() also exists, but strip() understands Unicode whitespace, so it is the better choice in modern code. isBlank() is true for a string that contains only spaces.
When comparing, == checks whether two references point to the same object, while equals() checks whether the characters match. Java shares literals like "java" in the string pool, so comparing two literals with == often happens to give true, which is exactly why this bug passes tests and only appears in production. Use equalsIgnoreCase() when case should not matter. If a variable might be null, call the method on the literal, as in "admin".equals(role); role.equals("admin") throws a NullPointerException when role is null.
| Method | Returns |
|---|---|
| s.length() | number of characters (int) |
| s.indexOf("x") | first index, or -1 if missing |
| s.substring(b, e) | new String from b up to e (exclusive) |
| s.strip() | new String without outer whitespace |
| s.equals(t) | true if the text is the same |
| s.contains("x") | true if the text occurs |
- Read the original String
- Create a new String for the result
- Return the new String
- The original stays untouched
If you do not store the returned value, the work is simply lost.
General pattern
String text = "literal";
int size = text.length();
String changed = text.method(arguments); // new String; text is unchanged
int position = text.indexOf("part"); // -1 when not found
String piece = text.substring(start, end); // end is exclusive
boolean same = text.equals(other); // compare content, never ==
boolean safe = "literal".equals(maybeNull); // null-safe comparisonCreate a String from a literal and call methods on it with a dot. Every method that changes text returns a new String, so store the result in a variable. Compare text with equals(), and keep a possibly-null value on the argument side.
Example: cleaning and splitting an email
Imagine a user typing an email into a form with stray spaces and capital letters. This example cleans the email, finds the @ and splits it into a user part and a domain part. The final two lines show the difference between == and equals() in action.
public class Main {
public static void main(String[] args) {
String title = "Java Tutorial";
String email = " Student@Example.com ";
System.out.println("Length: " + title.length());
System.out.println(title.toUpperCase());
System.out.println("Title unchanged: " + title);
String clean = email.strip().toLowerCase();
System.out.println("Clean: [" + clean + "]");
int at = clean.indexOf("@");
System.out.println("@ at index: " + at);
System.out.println("User: " + clean.substring(0, at));
System.out.println("Domain: " + clean.substring(at + 1));
String course = "ja";
course = course + "va";
System.out.println("course == java? " + (course == "java"));
System.out.println("course.equals(java)? " + course.equals("java"));
}
}Code breakdown
- Lines 7-8
System.out.println(title.toUpperCase());toUpperCase() returns a new String, "JAVA TUTORIAL", which is printed. The next line prints title again and it is still "Java Tutorial": that is immutability in practice.
- Line 10
String clean = email.strip().toLowerCase();strip() returns a new String without the outer spaces, and toLowerCase() is called on that new String. The final result is stored in clean, while email itself is unchanged.
- Line 12
int at = clean.indexOf("@");In "student@example.com", student occupies indexes 0-6, so the @ is at index 7. Without an @ the result would be -1, which real code must check for.
- Lines 14-15
System.out.println("Domain: " + clean.substring(at + 1));substring(0, at) takes index 0 up to but not including 7, giving "student". substring(at + 1) starts just after the @ and runs to the end, giving "example.com".
- Lines 17-20
System.out.println("course == java? " + (course == "java"));course + "va" is joined at runtime, producing a new object. == compares it with the pooled "java" literal, finds a different object and gives false; equals() compares the characters and gives true.
Length: 13
JAVA TUTORIAL
Title unchanged: Java Tutorial
Clean: [student@example.com]
@ at index: 7
User: student
Domain: example.com
course == java? false
course.equals(java)? trueStringBuilder, text blocks and formatted()
Because Strings are immutable, result = result + piece inside a loop creates a new String and copies the old text on every pass, which slows down with thousands of pieces. StringBuilder is a mutable buffer: you append() to it and call toString() once at the end. For multi-line text, use a text block (""" ... """) and fill placeholders with formatted(). String.join() puts a separator between items.
public class Main {
public static void main(String[] args) {
StringBuilder line = new StringBuilder();
line.append("HTML").append(", ").append("CSS").append(", ").append("Java");
System.out.println(line.toString());
String report = """
Name: %s
Score: %d
""".formatted("Aye", 92);
System.out.print(report);
System.out.println(String.join(" | ", "HTML", "CSS", "Java"));
System.out.println("ha".repeat(3) + " " + " ".isBlank());
}
}The output is HTML, CSS, Java, then Name: Aye, Score: 92, HTML | CSS | Java and hahaha true. Java removes the leading spaces up to the indentation of the closing """, so Name: starts at the beginning of its line.
In real projects
Where this shows up in real projects
Every sign-up form strips and lowercases emails and usernames before saving them, so "Aye@Mail.com " and "aye@mail.com" do not become two accounts. A search box lowercases what the user typed and matches it with contains() or a database query. File uploads use filename.lastIndexOf('.') to pull out the extension and check that the type is allowed.
Code that compares roles, status codes or command names often uses the "ADMIN".equals(role) form, which reviewers like because a request without a role does not crash. Log messages, email bodies and CSV rows are assembled with StringBuilder, String.join() and text blocks. Real apps never compare passwords as plain Strings; they check a stored hash with a security library. The problem section's code is kept simple only to show the == bug.
Common mistakes
Common mistakes
1. Comparing text with ==
Comparing two literals with == often gives true thanks to the string pool, so tests seem to pass. Strings that come from input, files or concatenation then give false. Always compare content with equals() or equalsIgnoreCase().
2. Throwing away a method's result
A bare name.strip(); line creates a new String that is immediately discarded, and name stays the same. Assign it back with name = name.strip();. IDEs often warn that the result of String.strip() is ignored, so do not dismiss that warning.
3. Thinking substring() includes the end index
"Java".substring(1, 3) is "av", not "ava", because the end index is excluded. And when indexOf() returns -1, calling substring(-1) throws a StringIndexOutOfBoundsException, so check for -1 first.
Mini challenge
Mini challenge: contact card checker
Write a program that takes a raw email and a full name, then prints the cleaned email, the name's initials and whether the email looks valid.
- normalize(raw): strip the outer spaces and lowercase it
- looksLikeEmail(email): exactly one @, not the first character, and a . at least one character after the @
- initials(fullName): first letter of the first and second words in capitals (just one letter for a single word)
- Try four inputs and match the expected output
public class Main {
static String normalize(String raw) {
// TODO: strip, then lowercase
return raw;
}
static boolean looksLikeEmail(String email) {
// TODO: compare indexOf('@') with lastIndexOf('@'), then look for a '.'
return false;
}
static String initials(String fullName) {
// TODO: find the first space; it may not exist (-1)
return "";
}
static void report(String rawEmail, String fullName) {
// TODO: print "AC <aye@mail.com> valid: true"
}
public static void main(String[] args) {
report(" Aye@Mail.COM ", "aye chan");
report("no-at-sign.com", "Min");
report("a@b@c.com", " su myat ");
report("kyaw@school.edu.mm", "Kyaw Zin");
}
}Expected: The program prints these four lines: AC <aye@mail.com> valid: true M <no-at-sign.com> valid: false SM <a@b@c.com> valid: false KZ <kyaw@school.edu.mm> valid: true
Show hint
If indexOf('@') equals lastIndexOf('@'), there is exactly one @. indexOf('.', at) starts searching at the @. For initials, strip() the name first and take the second word's letter with substring(space + 1, space + 2).
Show solution
public class Main {
static String normalize(String raw) {
return raw.strip().toLowerCase();
}
static boolean looksLikeEmail(String email) {
int at = email.indexOf('@');
boolean oneAt = at > 0 && at == email.lastIndexOf('@');
return oneAt && email.indexOf('.', at) > at + 1;
}
static String initials(String fullName) {
String name = fullName.strip();
int space = name.indexOf(' ');
String second = space < 0 ? "" : name.substring(space + 1, space + 2);
return (name.substring(0, 1) + second).toUpperCase();
}
static void report(String rawEmail, String fullName) {
String email = normalize(rawEmail);
boolean valid = looksLikeEmail(email);
System.out.println(initials(fullName) + " <" + email + "> valid: " + valid);
}
public static void main(String[] args) {
report(" Aye@Mail.COM ", "aye chan");
report("no-at-sign.com", "Min");
report("a@b@c.com", " su myat ");
report("kyaw@school.edu.mm", "Kyaw Zin");
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A String is an immutable object indexed from 0, and every method returns a new String.
- indexOf() returns -1 when nothing is found, and substring(begin, end) excludes end.
- Compare text with equals(); == only checks whether it is the same object.
- Clean user input with strip() and toLowerCase(), and use StringBuilder to build large texts.