Skip to content

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.

Beginner 18 min read·Lesson 8 of 39 in Java Programming

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

Java
String s = "Hello, Java";
s.length(); // 11
s.charAt(0); // 'H'
s.indexOf("Java"); // 7
s.substring(0, 5); // "Hello"
s.toUpperCase(); // "HELLO, JAVA" (s unchanged)
s.split(", "); // ["Hello", "Java"]
s.equals("Hello, Java"); // true
String.join("-", "a", "b");// "a-b"
  • Indexes start at 0; substring(b, e) excludes index e.
  • indexOf returns -1 when the text isn't found.
  • split takes a regular expression: split on a dot with split("\\.").

Code examples

Common methods

Java
public class Str {
public static void main(String[] args) {
String s = " Learning Java at KENHOLT ";
String t = s.trim();
System.out.println("[" + t + "] length " + t.length());
System.out.println(t.toUpperCase());
System.out.println(t.indexOf("Java") + " " + t.contains("Python"));
System.out.println(t.substring(9, 13));
System.out.println(t.replace("Java", "C++"));
System.out.println(t.charAt(0) + " " + t.charAt(t.length() - 1));
System.out.println("ab".repeat(3) + " " + " ".isBlank());
}
}
Output
[Learning Java at KENHOLT] length 24
LEARNING JAVA AT KENHOLT
9 false
Java
Learning C++ at KENHOLT
L T
ababab true

equals versus ==

Java
public class Compare {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // same pooled literal
System.out.println(a == c); // different objects
System.out.println(a.equals(c)); // same contents
System.out.println("Java".equalsIgnoreCase(a));
System.out.println("apple".compareTo("banana") < 0);
}
}
Output
true
false
true
true
true

More examples

Parsing a record and analysing text

Java
public class Parse {
public static void main(String[] args) {
String record = "Asha Rao, asha@example.com, CSE, 2nd year";
String[] parts = record.split(",\\s*");
System.out.println(parts.length + " fields");
String email = parts[1];
String user = email.substring(0, email.indexOf('@'));
String domain = email.substring(email.indexOf('@') + 1);
System.out.println("user=" + user + " domain=" + domain);
String sentence = "Java is fun and Java is everywhere";
int vowels = 0;
for (char ch : sentence.toLowerCase().toCharArray())
if ("aeiou".indexOf(ch) >= 0) vowels++;
System.out.println("vowels: " + vowels);
int count = 0, from = 0;
while ((from = sentence.indexOf("Java", from)) != -1) { count++; from += 4; }
System.out.println("'Java' appears " + count + " times");
String initials = "";
for (String w : parts[0].split(" ")) initials += w.charAt(0);
System.out.println("initials: " + initials + ", reversed name: " + new StringBuilder(parts[0]).reverse());
}
}
Output
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; substring before and after it extracts the user name and domain.
  • toCharArray() lets a for-each loop visit every character; "aeiou".indexOf(ch) >= 0 is a compact vowel test.
  • The while loop searches for "Java" repeatedly, starting each search just after the previous match.
  • new StringBuilder(...).reverse() reverses text efficiently; String itself has no reverse method because strings are immutable.

Expected output

Running “Parsing a record and analysing text” prints exactly:

TextOutput
4 fields
user=asha domain=example.com
vowels: 12
'Java' appears 2 times
initials: AR, reversed name: oaR ahsA

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

name.toUpperCase();
System.out.println(name); // unchanged

Prefer

name = name.toUpperCase();
System.out.println(name);

String methods return new strings; the original object never changes.

Calling methods on a null string

Avoid

if (input.equals("quit")) ... // NPE if input is null

Prefer

if ("quit".equals(input)) ...

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. Use codePointCount for 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

  1. 1
    Check whether a word is a palindrome, ignoring case.
  2. 2
    Count 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?
Practise this topic