Skip to main content
Java Basics
CHAPTER 10 Beginner

Strings in Java

Updated: May 17, 2026
5 min read

# CHAPTER 10

Strings in Java

1. Introduction

Strings are everywhere — usernames, emails, URLs, passwords, and messages. In Java, String is a non-primitive reference type and one of the most heavily used classes. Understanding String immutability and manipulation methods is critical for interviews and real-world applications.

2. Learning Objectives

  • Create and manipulate Strings.
  • Use essential String methods.
  • Understand String immutability and the String Pool.
  • Use StringBuilder and StringBuffer for mutable strings.
  • Compare Strings correctly with .equals() vs ==.

3. Creating Strings

java
12345
// String literal (uses String Pool)
String s1 = "Hello";

// Using new keyword (creates new object on Heap)
String s2 = new String("Hello");

4. String Immutability

Strings in Java are immutable — once created, their value cannot be changed. Any modification creates a new String object.
java
123
String name = "John";
name = name + " Doe";  // Creates a NEW String "John Doe"
// The original "John" is abandoned in memory
1234567
String Pool (Heap):
+--------+    +----------+
| "John" |    | "John Doe"|
+--------+    +----------+
   ^               ^
   |               |
  (old)          (new reference)

5. Essential String Methods

MethodDescriptionExample
length()Returns string length"Hello".length() → 5
charAt(i)Character at index i"Hello".charAt(0) → 'H'
substring(a, b)Extract portion"Hello".substring(1, 4) → "ell"
toLowerCase()Convert to lowercase"JAVA".toLowerCase() → "java"
toUpperCase()Convert to uppercase"java".toUpperCase() → "JAVA"
trim()Remove leading/trailing spaces" Hi ".trim() → "Hi"
contains(s)Check if contains substring"Hello".contains("ell") → true
indexOf(s)First occurrence index"Hello".indexOf("l") → 2
replace(a, b)Replace characters/substrings"Hello".replace('l', 'r') → "Herro"
split(regex)Split into array"a,b,c".split(",") → ["a","b","c"]
equals(s)Compare content"abc".equals("abc") → true
equalsIgnoreCase(s)Case-insensitive compare"ABC".equalsIgnoreCase("abc") → true
startsWith(s)Prefix check"Hello".startsWith("He") → true
endsWith(s)Suffix check"Hello".endsWith("lo") → true
isEmpty()Check if empty"".isEmpty() → true
java
12345
String text = "  Java Programming  ";
System.out.println(text.trim());                   // "Java Programming"
System.out.println(text.trim().toUpperCase());      // "JAVA PROGRAMMING"
System.out.println(text.trim().replace("Java", "Python")); // "Python Programming"
System.out.println(text.trim().length());           // 16

6. String Comparison: == vs .equals()

java
1234567
String a = "Hello";
String b = "Hello";
String c = new String("Hello");

System.out.println(a == b);        // true (same pool reference)
System.out.println(a == c);        // false (different memory locations!)
System.out.println(a.equals(c));   // true (same CONTENT)

Rule: Always use .equals() to compare String content. == compares memory addresses.

7. StringBuilder (Mutable Strings)

When you need to modify strings frequently (like in loops), use StringBuilder for performance.
java
1234567
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");       // "Hello World"
sb.insert(5, ",");         // "Hello, World"
sb.replace(0, 5, "Hi");   // "Hi, World"
sb.delete(2, 4);           // "Hi World"
sb.reverse();              // "dlroW iH"
System.out.println(sb.toString());

Why StringBuilder? String concatenation in a loop creates thousands of temporary String objects. StringBuilder modifies the same internal character array — much faster.

8. StringBuilder vs StringBuffer

FeatureStringBuilderStringBuffer
SpeedFasterSlower
Thread-safeNoYes (synchronized)
Use whenSingle-threadedMulti-threaded

9. Common Mistakes

  • Using == for String comparison: Always use .equals().
  • Concatenating in loops without StringBuilder: Causes O(n²) performance.
  • NullPointerException: Calling methods on a null String crashes.

10. MCQ Quiz with Answers

Question 1

Strings in Java are:

Question 2

Which compares String content correctly?

Question 3

What does "Hello".charAt(1) return?

Question 4

Which class creates mutable strings?

Question 5

What does trim() do?

Question 6

What is "abc".length()?

Question 7

String Pool is stored in:

Question 8

StringBuffer vs StringBuilder?

Question 9

"Hello".substring(0, 3) returns:

Question 10

What does split(",") do?

11. Interview Questions

  • Q: Why are Strings immutable in Java?
  • Q: What is the String Pool and how does it work?
  • Q: When should you use StringBuilder vs StringBuffer?
  • Q: What is the time complexity of String concatenation in a loop?

12. Summary

Strings are immutable objects in Java. Use .equals() for comparison, not ==. The String class provides dozens of utility methods. For mutable string operations, use StringBuilder (single-threaded) or StringBuffer (multi-threaded). Understanding the String Pool is a critical interview topic.

13. Next Chapter Recommendation

In Chapter 11: Methods in Java, we'll learn how to organize code into reusable blocks using methods, parameters, return types, and recursion.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·