Strings: Work with Text in Java
Introduction
In this chapter, you will learn how strings work in Java and how to process text effectively. Strings appear in user names, messages, file paths, and API payloads. Combined with Operators and Scanner, text handling unlocks much more practical programs.
Prerequisites
- Variables and basic
mainprograms - Familiarity with
+andprintln - JDK 21 and an editor
What Is a String
A String is a sequence of characters—letters, digits, symbols, and spaces.
String language = "Java";
String message = "Hello, world!";
System.out.println(language);
System.out.println(message);In Java, String is a reference type (a class), not a primitive. You will use it constantly before diving deep into custom classes.
1) Creating Strings
String city = "New York";
String country = "USA";
String note = "I'm learning Java."; // apostrophe inside double quotesText blocks (multi-line strings, Java 15+):
String poem = """
Roses are red,
Violets are blue.
""";2) Concatenation and +
Use + to join strings. Non-string values are converted to text automatically in many cases:
String firstName = "Ada";
String lastName = "Lovelace";
String fullName = firstName + " " + lastName;
int days = 13;
String msg = firstName + " has studied Java for " + days + " days.";
System.out.println(msg);For many values, chaining + in loops is inefficient—see StringBuilder below.
3) Comparing Strings: equals vs ==
==compares references (same object in memory?).equals()compares content (same characters?)
String a = new String("Java");
String b = new String("Java");
System.out.println(a == b); // false — different objects
System.out.println(a.equals(b)); // true — same textWarning
For text content, use .equals() (often with .equalsIgnoreCase() when case should not matter). Use == only when you intentionally check whether two references point to the same object.
String input = scanner.nextLine();
if ("quit".equalsIgnoreCase(input)) {
System.out.println("Goodbye!");
}Place the literal first ("quit".equals(input)) to avoid NullPointerException if input is null.
4) Useful String Methods
| Method | Purpose | Example |
|---|---|---|
length() | character count | "Java".length() → 4 |
charAt(i) | character at index | "Java".charAt(0) → 'J' |
substring(begin, end) | slice | "Hello".substring(0, 2) → "He" |
toUpperCase() / toLowerCase() | case change | |
strip() | trim whitespace (Java 11+) | " hi ".strip() → "hi" |
replace(old, new) | replace text | |
contains(text) | search | |
split(regex) | split into array |
String title = "java for beginners";
System.out.println(title.toUpperCase()); // JAVA FOR BEGINNERS
String rawName = " Alice ";
String cleanName = rawName.strip();
System.out.println(cleanName);
String sentence = "I like Python.";
System.out.println(sentence.replace("Python", "Java"));
String tagsText = "java,strings,basics";
String[] tags = tagsText.split(",");
for (String tag : tags) {
System.out.println(tag);
}Warning
String indices start at 0. charAt(length()) throws StringIndexOutOfBoundsException.
5) Strings Are Immutable
String objects cannot change after creation. Methods like replace and toUpperCase return new strings:
String original = "Java";
original.toUpperCase();
System.out.println(original); // still "Java"
String updated = original.toUpperCase();
System.out.println(updated); // "JAVA"Immutability makes strings safe to share but means heavy concatenation in loops creates many temporary objects.
6) StringBuilder and StringBuffer
For building text in loops, use StringBuilder (mutable, not thread-safe, preferred) or StringBuffer (thread-safe, slightly slower—legacy shared code).
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 5; i++) {
builder.append(i).append("-");
}
String result = builder.toString(); // "0-1-2-3-4-"
System.out.println(result);Rule of thumb:
- Few joins with
+→ fine - Many joins in a loop →
StringBuilder
7) Mini Example: Username Formatter
import java.util.Scanner;
public class UsernameFormatter {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your first name: ");
String first = scanner.nextLine().strip();
System.out.print("Enter your last name: ");
String last = scanner.nextLine().strip();
String displayName = first.substring(0, 1).toUpperCase() + first.substring(1).toLowerCase()
+ " "
+ last.substring(0, 1).toUpperCase() + last.substring(1).toLowerCase();
String accountId = (first + "." + last).toLowerCase();
System.out.println("Display Name: " + displayName);
System.out.println("Account ID: " + accountId);
}
}
}Surprise Practice: Secret Message Styler
Build a console tool that:
- Asks for a sentence (
Scanner.nextLine()) - Prints original, uppercase, reversed, and word count
- Prints a decorative border based on length
import java.util.Scanner;
public class SecretMessageStyler {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Type your message: ");
String text = scanner.nextLine().strip();
String upperText = text.toUpperCase();
String reversedText = new StringBuilder(text).reverse().toString();
int wordCount = text.isBlank() ? 0 : text.split("\\s+").length;
String border = "*".repeat(text.length() + 4);
System.out.println(border);
System.out.println("* " + text + " *");
System.out.println(border);
System.out.println("UPPER: " + upperText);
System.out.println("REVERSED: " + reversedText);
System.out.println("WORDS: " + wordCount);
}
}
}Fun output—and you practiced strip, split, StringBuilder.reverse(), and repeat().
Common Beginner Mistakes
Mistake 1: Using == to Compare Text
Use .equals() for content comparison.
Mistake 2: Forgetting strip() on Input
Leading/trailing spaces break comparisons and counts.
Mistake 3: Assuming Methods Change the Original
Assign or print the return value of methods like replace and toUpperCase.
Mistake 4: Concatenating in Tight Loops with +
Use StringBuilder when building large strings iteratively.
What’s Next
Learn reserved words in Keywords, then branch logic in Conditional Statements.
FAQ
Are strings mutable in Java?
No. String is immutable; mutating APIs return new strings (or use StringBuilder).
Should I use + or StringBuilder?
+ for simple joins; StringBuilder for repeated building in loops.
How do I reverse a string?
new StringBuilder(text).reverse().toString() is a common approach.
Why does indexing start at 0?
Same convention as arrays and many languages—first character is index 0.
What is the difference between StringBuilder and StringBuffer?
StringBuilder is faster for single-threaded code. StringBuffer is synchronized for legacy thread-safe scenarios. Prefer StringBuilder in new learning code.