Module 2 · Java Basics — topic 5 of 5
Strings
Creating and comparing strings, immutability and the string pool, the most useful String methods, text blocks and when to use StringBuilder.
Learning objectives
- Compare strings correctly with equals and compareTo
- Use common String methods to search, slice and transform text
- Explain immutability and its consequences
Definition
A String is an immutable sequence of characters represented by the java.lang.String class. Every method that seems to change a string returns a new String; the original is never modified.
Introduction
Names, messages, file contents, commands — text is everywhere. Java's String class has dozens of methods, but a dozen of them cover almost everything you will need, and one rule explains their behaviour: strings never change.
Why it matters
Comparing strings with == is one of the most frequent bugs in Java code.
Text processing — parsing commands, cleaning data, formatting reports — appears in nearly every project.
Detailed explanation
Creating strings. A literal such as "hello" creates (or reuses) a String in the *string pool*. new String("hello") always creates a new object — you rarely need it.
Immutability. s.toUpperCase() does not change s; it returns a new string. To keep the result, assign it: s = s.toUpperCase();. Immutability makes strings safe to share between objects and threads and lets them be used as map keys.
Comparison. a.equals(b) compares contents; a.equalsIgnoreCase(b) ignores case; a.compareTo(b) returns a negative number, zero or a positive number for alphabetical (Unicode) order. == only tells you whether two variables refer to the same object.
Useful methods. length(), charAt(i), indexOf(s), contains(s), startsWith, endsWith, substring(begin, end) (end exclusive), replace, trim() and strip(), toUpperCase, split(regex), String.join(sep, parts), repeat(n) (Java 11), isBlank() (Java 11) and chars().
Concatenation in loops. s += x inside a loop creates a new string each time, copying all previous characters — quadratic time. Use StringBuilder (next module) to build long strings.
Text blocks (Java 15). Triple-quoted literals span several lines and keep their formatting, which is ideal for JSON, SQL or help text: String help = """ followed by lines and a closing """. The common indentation is removed automatically.
Syntax
- Indexes start at 0;
substring(b, e)excludes index e. indexOfreturns -1 when the text isn't found.splittakes a regular expression: split on a dot withsplit("\\.").
Code examples
Common methods
[Learning Java at KENHOLT] length 24 LEARNING JAVA AT KENHOLT 9 false Java Learning C++ at KENHOLT L T ababab true
equals versus ==
true false true true true
More examples
Parsing a record and analysing text
4 fields user=asha domain=example.com vowels: 12 'Java' appears 2 times initials: AR, reversed name: oaR ahsA
Step-by-step explanation
split(",\\s*")splits on a comma followed by any amount of whitespace (\\s*in a Java string is the regex\s*), giving four clean fields.indexOf('@')finds the separator;substringbefore and after it extracts the user name and domain.toCharArray()lets a for-each loop visit every character;"aeiou".indexOf(ch) >= 0is a compact vowel test.- The
whileloop searches for "Java" repeatedly, starting each search just after the previous match. new StringBuilder(...).reverse()reverses text efficiently;Stringitself has no reverse method because strings are immutable.
Expected output
Running “Parsing a record and analysing text” prints exactly:
Practical applications
- Parsing CSV lines and command input
- Validating e-mail addresses and usernames
- Building messages and reports
- Normalising user input with trim and toLowerCase before comparing
Best practices
- Always compare contents with equals (or equalsIgnoreCase).
- Use StringBuilder when building a string in a loop.
- Normalise input (trim, toLowerCase) once, at the boundary where it enters your program.
Common mistakes
Forgetting strings are immutable
Avoid
Prefer
String methods return new strings; the original object never changes.
Calling methods on a null string
Avoid
Prefer
Calling equals on the literal is null-safe because the literal is never null.
Important notes
length()counts UTF-16 code units, so an emoji may count as 2. UsecodePointCountfor true character counts.strip()(Java 11) removes all Unicode whitespace;trim()removes only characters up to U+0020.
Key takeaways
- Strings are immutable; methods return new strings.
- Use equals for content, == only for identity.
- substring(b, e) excludes e; indexOf returns -1 when not found.
Try it yourself
- 1Check whether a word is a palindrome, ignoring case.
- 2Count the words in a sentence that may contain several spaces between words.
Show hint
split("\\s+") after trim().
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat is printed?
- BeginnerWhat is printed?