Java Tutorial chapters (15)
  1. 01Java Introduction
  2. 02Java Variables & Data Types
  3. 03Java Control Statements
  4. 04Java OOPs Basics
  5. 05Java Inheritance & Polymorphism
  6. 06Java Abstraction & Interfaces
  7. 07Java Strings
  8. 08Java Arrays
  9. 09Java Exception Handling
  10. 10Java Collections Framework
  11. 11Java Multithreading
  12. 12Java 8 Features
  13. 13Java I/O & File Handling
  14. 14Java JDBC
  15. 15Java MCQ

Chapter 07

Java Strings

4 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A String in Java is an immutable sequence of characters stored as an object.

This chapter covers creating strings, the most-used String methods, the mutable StringBuffer and StringBuilder classes, and the String constant pool that decides when == is true.

Strings appear in almost every Java program, and questions on immutability, == vs equals and the string pool are asked in nearly every interview.

Reading user input, building SQL and JSON text, validating emails, log messages, file names and URLs.

1

String in Java

String is a final class in java.lang that represents an immutable sequence of characters. A String object can be created with a literal (String s = "Java";) or with the new keyword (new String("Java")). Once created, its contents can never change.

In short: A String is a piece of text that is locked after it is written. Every change creates a brand-new piece of text.

String as indexed characters

Think about it

Text handling is needed everywhere. Immutability makes strings safe, cacheable and secure (for example for file paths, class names and network connections). A printed certificate: you cannot edit the printed words; to change a word you print a new certificate.

Internally a String holds a char/byte array that is private and final, and the class itself is final, so nobody can subclass it and break immutability.

Because of this, Strings are thread-safe, safe to use as HashMap keys (the hash code can be cached) and safe to share through the string pool.

Methods such as concat, replace, toUpperCase and substring do NOT change the original; they return a new String, so you must store the result.

The == operator compares references (are both variables pointing to the same object?

) while equals() compares the characters.

Always compare text with equals().

To avoid NullPointerException use `"literal".

equals(variable)`.

Strings implement Comparable, CharSequence and Serializable.

Concatenation with + creates new objects; inside a loop prefer StringBuilder.

Key points

  • Immutable: Object state cannot change after creation.
  • String literal: Text in double quotes; stored in the string pool.
  • equals(): Compares the character content of two strings.
  • ==: Compares whether two references point to the same object.
  • compareTo(): Lexicographic comparison; returns negative, zero or positive.
  • String is final, immutable and implements Comparable<String>, CharSequence, Serializable.
  • Two ways to create: literal (pool) and new (heap, always a new object).
  • Never use == to compare string content; use equals() or equalsIgnoreCase().
  • concat() and + create a new string; the original is untouched.

Example

Code
Creating strings, immutability and equals vs ==:
public class StringBasics {
    public static void main(String[] args) {
        String a = "Java";
        String b = "Java";
        String c = new String("Java");

        System.out.println(a == b);        // true  (same pooled object)
        System.out.println(a == c);        // false (c is a new heap object)
        System.out.println(a.equals(c));   // true  (same characters)

        String s = "Hello";
        s.concat(" World");                // result is thrown away
        System.out.println(s);             // Hello
        s = s.concat(" World");            // store the new String
        System.out.println(s);             // Hello World

        System.out.println("apple".compareTo("banana")); // -1  ('a' - 'b')
        System.out.println("Java".equalsIgnoreCase("JAVA")); // true

        String name = null;
        System.out.println("admin".equals(name));        // false, no NullPointerException
        System.out.println(name + "!");                  // null!
    }
}
2

String Methods in Java

String methods are the built-in operations of the String class used to inspect, search, extract, compare, convert and split text, for example length(), charAt(), substring(), indexOf(), contains(), replace(), split(), trim() and toUpperCase().

In short: Methods are the toolbox for text. Each tool gives you an answer or a new string; the original string never changes.

Think about it

Most string programs (palindrome, reverse, count vowels, anagram, validate) are built entirely from these methods. Cleaning a form field: trim the spaces, convert to lower case, split the full name into first and last name.

Indexing starts at 0 and the last valid index is length()-1; charAt with a bad index throws StringIndexOutOfBoundsException.

substring(begin, end) includes begin and excludes end.

indexOf returns -1 when nothing is found.

trim() removes leading/trailing spaces (<= U+0020); strip() (Java 11) is Unicode-aware; isBlank() is true for empty or whitespace-only text.

split(regex) takes a regular expression, so special characters such as ".

" and "|" must be escaped ("\\.

" in source).

`String.

join(delim, items)` is the reverse of split.

valueOf converts primitives to String, toCharArray() gives a char[] (handy for sorting characters), and `String.

format / formatted` build text using %d, %s, %.

2f.

repeat(n) (Java 11) repeats a string.

Since every method returns a new String, calls can be chained.

Key points

  • Index: Position of a character, starting at 0.
  • Substring: Part of a string from begin (inclusive) to end (exclusive).
  • Regex: Pattern language used by split, replaceAll and matches.
  • Lexicographic order: Dictionary order based on Unicode values of characters.

Example

Code
Frequently used String methods:
import java.util.Arrays;

public class StringMethodsDemo {
    public static void main(String[] args) {
        String s = "  Hello Java World  ";
        String t = s.trim();                         // "Hello Java World"

        System.out.println(t.length());              // 16
        System.out.println(t.charAt(4));             // o
        System.out.println(t.substring(6, 10));      // Java
        System.out.println(t.indexOf("a"));          // 7
        System.out.println(t.lastIndexOf("a"));      // 9
        System.out.println(t.indexOf("xyz"));        // -1
        System.out.println(t.contains("Java"));      // true
        System.out.println(t.toUpperCase());         // HELLO JAVA WORLD
        System.out.println(t.replace('l', 'L'));     // HeLLo Java WorLd

        String[] parts = t.split(" ");
        System.out.println(Arrays.toString(parts));  // [Hello, Java, World]
        System.out.println(String.join("-", parts)); // Hello-Java-World

        System.out.println("   ".isBlank());         // true
        System.out.println("Hi".repeat(3));          // HiHiHi
        System.out.println(String.format("%05d|%.2f|%s", 42, 3.14159, "ok")); // 00042|3.14|ok

        // Palindrome check using only String methods
        String w = "madam";
        String rev = new StringBuilder(w).reverse().toString();
        System.out.println(w.equals(rev));           // true

        // Count vowels
        int vowels = 0;
        for (char ch : "education".toCharArray()) {
            if ("aeiou".indexOf(ch) != -1) vowels++;
        }
        System.out.println(vowels);                  // 5
    }
}

Inspect

length(), isEmpty(), isBlank(), charAt(i), startsWith(), endsWith(), contains().

Search

indexOf(), lastIndexOf() return the position or -1.

Extract and change

substring(), replace(), trim(), strip(), toUpperCase(), toLowerCase(), repeat().

Split and join

split(regex) gives String[]; String.

join(delim, parts) rebuilds text.

Convert

toCharArray(), String.

valueOf(x), String.

format(), Integer.

parseInt(s).

3

StringBuffer vs StringBuilder

StringBuffer and StringBuilder are mutable sequences of characters in java.lang. StringBuffer is thread-safe (its methods are synchronized) and slower; StringBuilder (Java 5) has the same API but is not synchronized, so it is faster in single-threaded code.

In short: String is a printed page. StringBuilder is a whiteboard you can edit quickly. StringBuffer is the same whiteboard but with a lock on the door.

Mutable string builders

Think about it

Building large text with + inside loops wastes memory and time. Knowing the three classes is a guaranteed interview question. Generating a report with thousands of lines, or building a SQL query piece by piece.

Both keep a resizable char buffer.

The default capacity is 16; new StringBuilder("abc") has capacity 16 + 3 = 19.

When the buffer is full it grows to (oldCapacity × 2) + 2.

append, insert, delete, deleteCharAt, replace, reverse and setCharAt change the SAME object and return this, which allows chaining.

Neither class overrides equals() or hashCode(), so `sb1.

equals(sb2)` is false even for equal text; compare with `sb1.

toString().

equals(sb2.

toString())`.

Repeated s += x in a loop creates a new String every time, which is O(n²); a StringBuilder makes it O(n).

Rule of thumb: use String for constants, StringBuilder for local text building, StringBuffer only when several threads share one buffer (and even then, external locking is often cleaner).

Key points

Example

Code
Mutable text with StringBuilder and StringBuffer:
public class BuilderDemo {
    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        System.out.println(sb.capacity());               // 16
        System.out.println(new StringBuilder("abc").capacity()); // 19

        sb.append("Hello").append(' ').append("World");  // chaining
        System.out.println(sb);                          // Hello World
        sb.insert(0, ">>");
        System.out.println(sb);                          // >>Hello World
        sb.deleteCharAt(0).deleteCharAt(0);
        sb.setCharAt(0, 'J');
        System.out.println(sb);                          // Jello World
        sb.replace(0, 5, "Hi");
        System.out.println(sb);                          // Hi World
        System.out.println(sb.reverse());                // dlroW iH
        System.out.println(sb.length());                 // 8

        StringBuilder x = new StringBuilder("same");
        StringBuilder y = new StringBuilder("same");
        System.out.println(x.equals(y));                 // false
        System.out.println(x.toString().equals(y.toString())); // true

        // Speed comparison idea: concatenation in a loop
        String slow = "";
        for (int i = 0; i < 5; i++) slow += i;           // 5 temporary Strings
        StringBuilder fast = new StringBuilder();
        for (int i = 0; i < 5; i++) fast.append(i);      // one buffer
        System.out.println(slow + " " + fast);           // 01234 01234

        StringBuffer safe = new StringBuffer("log");
        safe.append(":ready");                           // synchronized methods
        System.out.println(safe);                        // log:ready
    }
}
4

String Pool in Java

The String pool (string constant pool / intern pool) is a special area of the heap where the JVM stores unique string literals so that identical literals share one object. `String.intern()` returns the pooled instance for a given string.

In short: The JVM keeps one copy of every literal text. If you write "Java" ten times, all ten variables point to the same object.

String pool: reuse same literal text

Think about it

The pool explains the classic output-prediction questions and shows why immutability is required: shared objects must never change. A shared library book: many students borrow the same copy rather than printing a copy each.

When the compiler sees a literal, the JVM looks in the pool: if an equal string exists it reuses it, otherwise it adds it.

So "Java" == "Java" is true.

`new String("Java")` always creates a new object on the heap (and the literal "Java" is also placed in the pool if not present), which is why `new String("Java") == "Java"` is false.

Since Java 7 the pool lives in the heap (earlier it was in PermGen) so unused pooled strings can be garbage collected.

Compile-time constants are folded: "Ja" + "va" becomes the literal "Java" and equals the pooled one, and so does `final String f = "Ja"; f + "va"`.

But a non-final variable y + "va" is computed at runtime and creates a new heap object.

Calling intern() on such a string returns the pooled copy.

The pool saves memory and makes literal comparison fast, but never rely on == for content.

Key points

  • String constant pool: Heap area holding unique literal strings.
  • intern(): Returns the canonical pooled string equal to this one.
  • Compile-time constant: Expression made of literals/final constants that the compiler evaluates.
  • Heap object: Object created with new, stored outside the pool.
  • Literal: pool. new String("x"): heap object (plus pooled literal x).
  • new String("Java") creates up to 2 objects; a literal creates at most 1.
  • Since Java 7 the pool is part of the heap, not PermGen.
  • Use intern() only for rare memory-saving cases.

Example

Code
String pool, new and intern():
public class PoolDemo {
    public static void main(String[] args) {
        String s1 = "Java";
        String s2 = "Java";
        String s3 = new String("Java");
        String s4 = s3.intern();

        System.out.println(s1 == s2);   // true
        System.out.println(s1 == s3);   // false
        System.out.println(s1 == s4);   // true  (intern returns pooled copy)

        System.out.println("Ja" + "va" == s1);   // true  (constant folding)

        final String f = "Ja";
        System.out.println(f + "va" == s1);      // true  (f is a constant)

        String y = "Ja";
        String z = y + "va";                     // computed at run time
        System.out.println(z == s1);             // false
        System.out.println(z.intern() == s1);    // true
        System.out.println(z.equals(s1));        // true
    }
}

Solved examples

Example 01 · Basic

Predict the output: String a = "hi"; String b = new String("hi"); System.out.println((a == b) + " " + a.equals(b));

Given Data:
    Required To Find:

    Two booleans

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: a points to the pooled literal "hi"
    Step 2: b points to a new heap object
    Step 3: == is false because references differ, equals is true because characters match
    Final Answer: false true

    Approach note: Literal vs new is the favourite trick in output questions.

    Example 02 · Basic

    Count the vowels in "Programming" using String methods.

    Given Data:
      Required To Find:

      Number of vowels

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Convert to lower case
      Step 2: Loop over toCharArray()
      Step 3: If "aeiou".indexOf(ch) != -1 increment the counter
      Final Answer: 3 (o, a, i)

      Approach note: indexOf on a constant vowel string is shorter than five comparisons.

      Example 03 · Intermediate

      What does this print? String s = "abc"; s.toUpperCase(); s.concat("d"); System.out.println(s);

      Given Data:
        Required To Find:

        Printed text

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: toUpperCase() returns a new string that is ignored
        Step 2: concat("d") also returns a new string that is ignored
        Step 3: s still refers to the original object
        Final Answer: abc

        Approach note: If you do not assign the returned String, nothing is saved.

        Example 04 · Intermediate

        Reverse the words of "java is fun" to get "fun is java".

        Given Data:
          Required To Find:

          Reversed sentence

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: String[] w = s.split(" ")
          Step 2: Loop from the last index to 0
          Step 3: append each word and a space to a StringBuilder, then trim()
          Final Answer: fun is java

          Approach note: Reversing characters (sb.reverse()) is different from reversing word order.

          Real-world applications

          Java

          Using Java Strings in real projects

          Reading user input, building SQL and JSON text, validating emails, log messages, file names and URLs.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: s.toUpperCase() changes the string s.

          Why this is wrong: Strings are immutable, so the method returns a new String.

          ✅ Verified Truth: Assign the result: s = s.toUpperCase().

          ⚠️ Exam Tip: Immutability output questions appear in every Java paper.

          ❌ Myth: == and equals() are the same for strings.

          Why this is wrong: == compares references, equals() compares content.

          ✅ Verified Truth: Use equals() for content; == only for reference identity.

          ⚠️ Exam Tip: Literal == literal is true, new String == literal is false.

          ❌ Myth: StringBuilder is thread-safe.

          Why this is wrong: Only StringBuffer has synchronized methods.

          ✅ Verified Truth: Use StringBuffer or external locking for shared buffers.

          ⚠️ Exam Tip: Remember: Builder = faster, Buffer = safer.

          ❌ Myth: new String("a") creates exactly one object.

          Why this is wrong: The literal "a" may also be created in the pool.

          ✅ Verified Truth: It can create two objects: one in the pool, one on the heap.

          ⚠️ Exam Tip: Classic interview question: how many objects are created?

          Revision notes

          A String in Java is an immutable sequence of characters stored as an object. This chapter covers creating strings, the most-used String methods, the mutable StringBuffer and StringBuilder classes, and the String constant pool that decides when == is true.

          High-Yield Quick Revision Points

          1. String is final and immutable; methods return new strings
          2. Use equals() for content; == compares references
          3. substring(begin, end) excludes end; indexOf returns -1 when absent
          4. StringBuilder: fast, not thread-safe. StringBuffer: synchronized
          5. Literals share one pooled object; new String always creates a new one
          6. intern() returns the pooled string

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which class is immutable?

          Question 2 · MCQ (Interview / semester)

          What is the output of "Java".substring(1, 3)?

          Question 3 · MCQ (Interview / semester)

          What does "abc".compareTo("abd") return?

          Question 4 · MCQ (Interview / semester)

          Which is faster in single-threaded code?

          Question 5 · MCQ (Interview / semester)

          What is the default capacity of new StringBuilder()?

          Question 6 · MCQ (Interview / semester)

          Where are string literals stored?