Strings

Comprehensive study notes, diagrams, and exam preparation for Strings.

Strings

Definition

A string is a sequence of characters treated as a single value or object. It may contain letters, digits, spaces, symbols, and special characters.

In Java, a string is represented by the String class and is immutable, which means once a string object is created, its content cannot be changed. If any modification is required, a new string object is created instead.

Example:

String name = "Computer";

Here, "Computer" is a string made up of characters stored together as one value.


Main Content

1. String Basics and Creation

  • Strings can be created using string literals or the new keyword.
  • Common examples:
  String a = "Hello";
  String b = new String("Hello");
  • String literals are stored in the string pool, which helps memory reuse and improves performance.
  • String objects created with new are stored in heap memory as separate objects.
  • Strings can include:
  • Alphabets: "Java"
  • Numbers: "2025"
  • Mixed content: "User123"
  • Special characters: "@#%!"
  • Spaces: "Hello World"
  • The length of a string can be found using length():
  String text = "Hello";
  System.out.println(text.length()); // 5

String Pool Concept

When the same literal is used multiple times, Java may refer to the same object in memory.

String s1 = "Test";
String s2 = "Test";

Both s1 and s2 may point to the same object in the string pool.

Simple memory view:

String Pool:
   "Test"  <-- s1
            <-- s2

This reduces memory usage and increases efficiency.


2. Immutability and String Operations

  • Strings are immutable, meaning their value cannot be changed after creation.
  • Example:
  String s = "Java";
  s.concat(" Programming");
  System.out.println(s); // Java

The original string remains unchanged because concat() creates a new string.

  • Immutability provides:
  • Security
  • Thread safety
  • Reliable caching
  • Efficient string pooling
  • Common string operations include:
  • charAt(index) – returns a character at a given position
  • substring(start, end) – extracts part of a string
  • toUpperCase() / toLowerCase() – changes case
  • trim() – removes leading and trailing spaces
  • replace() – replaces characters or text
  • contains() – checks whether a sequence exists
  • equals() – compares content
  • compareTo() – compares lexicographically

Example:

String word = "Programming";
System.out.println(word.charAt(0));      // P
System.out.println(word.substring(0, 4)); // Prog
System.out.println(word.toUpperCase());   // PROGRAMMING

String Comparison

A very important point in strings is the difference between == and equals().

  • == checks whether two references point to the same object.
  • equals() checks whether the contents are the same.

Example:

String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println(s1 == s2);      // false
System.out.println(s1.equals(s2)); // true

This is one of the most common concepts in string handling.


3. StringBuffer and StringBuilder

  • Since normal strings are immutable, repeated modifications can create many temporary objects.
  • To handle mutable text efficiently, Java provides:
  • StringBuffer
  • StringBuilder
  • Both allow text modification without creating a new object each time.

StringBuffer

  • Mutable
  • Thread-safe
  • Slower than StringBuilder due to synchronization

Example:

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Hello World

StringBuilder

  • Mutable
  • Not thread-safe
  • Faster and preferred in single-threaded programs

Example:

StringBuilder sbr = new StringBuilder("Java");
sbr.append(" Language");
System.out.println(sbr); // Java Language

Comparison Diagram

String      -> immutable -> new object for every change
StringBuffer -> mutable   -> modifies same object, thread-safe
StringBuilder-> mutable   -> modifies same object, faster

Why Use Mutable String Classes?

  • When many concatenations are needed
  • When performance matters
  • When building large text dynamically
  • When working in loops where repeated + operations are inefficient

Example of inefficient use:

String result = "";
for (int i = 0; i < 1000; i++) {
    result = result + i;
}

Better approach:

StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    result.append(i);
}

Working / Process

  1. A string is created using either a literal or an object constructor.
  2. Java stores and manages the string, often reusing literals through the string pool.
  3. String methods are applied to search, compare, modify, or format the text as needed.

Advantages / Applications

  • Strings are essential for storing and processing text in programs.
  • They are widely used in user input, file handling, web applications, and database operations.
  • String-related classes like StringBuffer and StringBuilder improve efficiency in dynamic text processing.

Summary

  • String means a sequence of characters used to represent text.
  • In Java, String objects are immutable, while StringBuffer and StringBuilder are mutable.
  • Strings are used for storing, comparing, searching, and modifying text in nearly all applications.
  • Important terms to remember: String, immutability, string pool, equals(), substring(), StringBuffer, StringBuilder