Java Strings Unlocked: A Complete Guide Every Java Developer Should Know

Strings in Java

Learn everything about Java Strings—from creation, immutability, String Constant Pool, memory management, String methods, StringBuffer, StringBuilder, interview questions, and much more.

Complete Beginner to Advanced Guide
"Strings are the most frequently used objects in Java."

What is a String?

A String is simply a sequence of characters.

In Java, anything enclosed within double quotes (" ") is treated as a String.

String language = "Java"; String city = "Hyderabad"; String website = "Roadmap For Java";

Unlike primitive data types such as int, char, or boolean, a String is an object.

Definition

String is a sequence of characters represented by the predefined String class available in the java.lang package.

Important Notes:
  • String is a predefined class.
  • String objects are immutable.
  • Strings are stored inside the String Constant Pool whenever possible.
  • String belongs to the java.lang package, so importing it is unnecessary.

Why are Strings Important?

Almost every Java application works with text. Whether you're developing a website, Android application, desktop software, REST API, banking application, or an enterprise project, Strings are everywhere.

Application AreaExample
User Name"Ravi"
Password"Admin@123"
Email"abc@gmail.com"
File Name"report.pdf"
City"Hyderabad"
JSON Data"name":"John"
Database Values"Employee"
Real World Fact

More than 70% of objects created in a typical Java application are Strings. That's why Java provides several optimizations like the String Constant Pool and immutable String objects.

Characteristics of Strings

  • ✔ String is a predefined class.
  • ✔ String represents a sequence of Unicode characters.
  • ✔ String objects are immutable.
  • ✔ String supports object-oriented programming.
  • ✔ String literals are stored inside the String Constant Pool.
  • ✔ Multiple variables can safely share the same String object.
  • ✔ String provides many built-in methods for text manipulation.
  • ✔ String belongs to the java.lang package.

String is a Class

Many beginners think String is a primitive data type. It is not. String is a normal Java class provided by Java itself.

public final class String { ... }

Notice the keyword final. Since the String class is declared as final, it cannot be inherited.

Interview Question

Is String a primitive data type?

Answer: No. String is a predefined final class available in the java.lang package.

Basic String Declaration

String s = "Java";

Here,

  • String → Class name
  • s → Reference variable
  • "Java" → String literal
Don't confuse a String with a char!
charString
'A'"A"
Stores one characterStores multiple characters
Primitive datatypeObject
Uses single quotesUses double quotes

Example Program

public class StringDemo { public static void main(String[] args) { String course = "Java Programming"; System.out.println(course); } }
Output:

Java Programming

Two Ways to Create a String in Java

Java provides two distinct ways to create a String object. Even though the resulting text might be identical, the underlying memory allocation and object creation behavior are fundamentally different.

Ways to Create a String Object:

  1. Using a String Literal (e.g., String s = "Java";)
  2. Using the new Keyword (e.g., String s = new String("Java");)

1. String Creation Using String Literals

When you create a String using double quotes, Java leverages String Interning. Before creating a new object, the JVM searches the String Constant Pool (SCP).

  • If the literal already exists in the SCP, Java simply returns a reference to that existing object.
  • If the literal does not exist, a new String object is created inside the SCP.
String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true (points to same object)

2. String Creation Using the new Keyword

When you use the new operator, Java is forced to create a new object in the Heap Memory regardless of whether the same string literal already exists in the SCP.

String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); // false (different Heap addresses)

Deep Dive: How Many Objects Are Created? (Detailed Examples)

Understanding how many objects are created in memory (Heap vs SCP) is a classic interview domain. Let's analyze multiple scenarios step by step assuming a clean, newly started JVM state.

Example 1: Literal Assignment

String s1 = "Hello"; String s2 = "Hello";

Analysis:

  • s1 = "Hello" checks SCP. "Hello" is not present, so 1 object is created in the SCP.
  • s2 = "Hello" checks SCP. "Hello" is already present, so 0 new objects are created. s2 points to the same object as s1.
  • Total Objects Created: 1 Object (in SCP).

Example 2: Using new Keyword

String s1 = new String("Java");

Analysis:

  • 1 Object created in the Heap Memory because of the new keyword.
  • 1 Object created in the String Constant Pool for the literal "Java" (if not already present).
  • Total Objects Created: 2 Objects (1 in Heap, 1 in SCP).

Example 3: Multiple new Calls with Same Literal

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

Analysis:

  • Line 1: 1 object in Heap + 1 object in SCP = 2 objects.
  • Line 2: 1 object in Heap (because of new). Literal "Python" already exists in SCP, so no new SCP object is created.
  • Total Objects Created: 3 Objects (2 in Heap, 1 in SCP).

Example 4: Mixed Literals and new Keyword

String s1 = "Code"; String s2 = new String("Code"); String s3 = "Code"; String s4 = new String("Code");

Analysis:

  • s1 = "Code": 1 object created in SCP.
  • s2 = new String("Code"): 1 object created in Heap. (SCP already has "Code").
  • s3 = "Code": Reuses "Code" from SCP (0 objects).
  • s4 = new String("Code"): 1 object created in Heap. (SCP already has "Code").
  • Total Objects Created: 3 Objects (1 in SCP, 2 in Heap).

Example 5: String Concatenation with Literals vs Variables

String s1 = "Data"; String s2 = "Base"; String s3 = "Data" + "Base"; // Compile-time constant expression String s4 = s1 + s2; // Runtime expression

Analysis:

  • "Data" and "Base" create 2 objects in SCP.
  • s3 = "Data" + "Base" is resolved at compile-time by the Java compiler into "DataBase". 1 object is created in SCP.
  • s4 = s1 + s2 involves variables, so it is evaluated at runtime using StringBuilder. 1 new object is created in the Heap.
  • Total Objects Created: 4 Objects (3 in SCP: "Data", "Base", "DataBase"; 1 in Heap).

What is the String Constant Pool (SCP)?

The String Constant Pool (SCP) is a special, dedicated memory region inside the Java Heap Memory specifically designated to store String literals.

Heap Memory Area +-------------------------------------------------------+ | | | [Heap Objects] | | s2 ---------> [ "Java" (Heap Object) ] | | | | | v | | +-----------------------------------------------+ | | | String Constant Pool (SCP) | | | | | | | | s1 -------> [ "Java" (Literal) ] | | | | | | | +-----------------------------------------------+ | | | +-------------------------------------------------------+
Interview Architecture Insight:
  • Java 6 and earlier: SCP was located in the PermGen (Permanent Generation) space, which had fixed memory size, causing frequent java.lang.OutOfMemoryError: PermGen space.
  • Java 7 and later: SCP was relocated to the main Heap Memory space, allowing garbage collectors to reclaim unused literal references efficiently.

Immutability of Strings

Definition of Immutability

An object is said to be immutable if its state or value cannot be modified after it is created.

When you attempt to alter a String instance in Java—such as changing characters, appending content, or converting case—Java does not change the memory content of the existing object. Instead, it allocates a completely new String object containing the modified value.

Code Verification of Immutability

public class ImmutabilityTest { public static void main(String[] args) { String original = "Roadmap"; // Appending text using concat() original.concat(" For Java"); System.out.println("String Value: " + original); } }
Output:

String Value: Roadmap

To capture the modified value, you must assign the return result to a variable:

String original = "Roadmap"; original = original.concat(" For Java"); // Reassigns reference to new Heap/SCP object System.out.println("Updated Value: " + original); // Roadmap For Java

4 Key Reasons Why Strings Are Made Immutable

  1. String Pool Optimization: Sharing pooled literal references would be dangerous if Strings were mutable. If variable A changed its value, variable B pointing to the same pooled reference would get modified unintentionally!
  2. Security Features: Parameters like database connection strings, network socket URLs, and file access paths are passed as Strings. Immutability guarantees that malicious code cannot modify access credentials post-validation.
  3. Thread Safety: Immutable objects are inherently thread-safe and read-only. Multiple concurrent threads can safely read from shared String references without needing complex lock synchronizations.
  4. HashCode Caching: Because the contents never change, Java calculates and caches the String's hashCode() during creation. This provides major performance boosts when using Strings in hash-based collections like HashMap and HashSet.

Complete String Class Constructors

Although creating Strings using literals is standard, the java.lang.String class provides multiple constructors to create String objects from character arrays, byte arrays, buffers, and existing strings.

Constructor SignatureDescription
String() Creates an empty String object (contains "").
String(String original) Creates a new String object containing a copy of the specified String object.
String(char[] value) Allocates a new String representing the sequence of characters in the array.
String(char[] value, int offset, int count) Allocates a new String from a sub-array of characters starting at offset.
String(byte[] bytes) Constructs a new String by decoding the byte array using the platform's default charset.
String(byte[] bytes, int offset, int length) Constructs a String by decoding a sub-array of bytes.
String(StringBuffer buffer) Allocates a new String containing the character sequence currently in the StringBuffer.
String(StringBuilder builder) Allocates a new String containing the character sequence currently in the StringBuilder.

Code Example: Using String Constructors

public class StringConstructorsDemo { public static void main(String[] args) { // 1. From char array char[] charArr = {'J', 'a', 'v', 'a'}; String s1 = new String(charArr); // 2. From byte array (ASCII values) byte[] byteArr = {72, 69, 76, 76, 79}; // "HELLO" String s2 = new String(byteArr); // 3. Sub-array of char String s3 = new String(charArr, 0, 2); // "Ja" System.out.println("s1: " + s1); System.out.println("s2: " + s2); System.out.println("s3: " + s3); } }
Output:

s1: Java
s2: HELLO
s3: Ja

Comprehensive List of String Class Methods

Here is an exhaustive list of important methods provided by the String class:

MethodReturn TypeDescription
charAt(int index)charReturns the character at the specified index.
length()intReturns the total length of the string.
concat(String str)StringAppends specified string to the end.
contains(CharSequence s)booleanReturns true if sequence exists in string.
startsWith(String prefix)booleanChecks if string starts with given prefix.
endsWith(String suffix)booleanChecks if string ends with given suffix.
equals(Object anObject)booleanCompares content equality.
equalsIgnoreCase(String anotherString)booleanCompares content ignoring case.
indexOf(String str)intReturns index of first occurrence of substring.
lastIndexOf(String str)intReturns index of last occurrence of substring.
isEmpty()booleanReturns true if length is 0.
isBlank() (Java 11+)booleanReturns true if string is empty or contains only whitespace.
replace(char old, char new)StringReplaces old characters with new characters.
replaceAll(String regex, String replacement)StringReplaces matches of regex with replacement.
split(String regex)String[]Splits string into array around regex matches.
substring(int beginIndex)StringExtracts substring from index to end.
substring(int begin, int end)StringExtracts substring from begin to end index.
toLowerCase() / toUpperCase()StringConverts casing of character contents.
trim() / strip()StringRemoves leading and trailing whitespaces.
valueOf(anyType)String (static)Converts primitive types or objects to String.
toCharArray()char[]Converts String into a fresh character array.

Complete String Methods Breakdown

Below is a comprehensive guide to essential methods in the java.lang.String class with code examples for each.

1. Basic Inspection Methods

length() returns the character count, charAt(index) fetches a specific character, and substring() extracts a portion of the text.

public class BasicStringMethods { public static void main(String[] args) { String str = "Java Programming"; System.out.println("Length: " + str.length()); // 16 System.out.println("Character at index 5: " + str.charAt(5)); // 'P' System.out.println("Substring from index 5: " + str.substring(5)); // "Programming" System.out.println("Substring (0 to 4): " + str.substring(0, 4)); // "Java" } }

2. String Comparison Methods

Use equals(), equalsIgnoreCase(), and compareTo() for value checking.

public class StringComparisonMethods { public static void main(String[] args) { String s1 = "JAVA"; String s2 = "java"; System.out.println("equals(): " + s1.equals(s2)); // false System.out.println("equalsIgnoreCase(): " + s1.equalsIgnoreCase(s2)); // true System.out.println("compareTo(): " + s1.compareTo(s2)); // Non-zero integer (-32) } }

3. Search, Replace & Splitting Methods

Search using contains() or indexOf(), replace text using replace(), or tokenize strings using split().

public class SearchTransformDemo { public static void main(String[] args) { String data = "Apple,Banana,Cherry"; // Searching System.out.println("Contains 'Banana': " + data.contains("Banana")); // true System.out.println("Index of 'Cherry': " + data.indexOf("Cherry")); // 13 // Replacing String updated = data.replace("Apple", "Mango"); System.out.println("Replaced String: " + updated); // Splitting String[] fruits = data.split(","); for (String fruit : fruits) { System.out.println("Fruit: " + fruit); } } }

What is StringBuffer in Java?

The StringBuffer class is a mutable, thread-safe sequence of characters provided in the java.lang package. Unlike the String class, objects created using StringBuffer can be modified directly in memory without creating new objects during each alteration.

Key Characteristics of StringBuffer:

  • ✔ Mutable: Modifications (append, insert, delete, reverse) alter the existing object in memory.
  • ✔ Thread-Safe: All public methods in StringBuffer are synchronized, making it safe for access by multiple threads concurrently.
  • ✔ Stored in Heap Memory: StringBuffer objects are stored in the Heap memory, not in the String Constant Pool.
  • ✔ Dynamic Capacity: Automatically expands its internal character array buffer as new text is added.
Interview Question: Why is StringBuffer thread-safe?

Answer: Because its methods are explicitly marked with the synchronized keyword, preventing data corruption when multiple threads modify the same StringBuffer instance simultaneously.


StringBuffer Constructors

The StringBuffer class provides four distinct constructors to initialize the buffer:

ConstructorDescriptionInitial Capacity
StringBuffer() Creates an empty StringBuffer with default initial capacity. 16 characters
StringBuffer(int capacity) Creates an empty StringBuffer with a specified initial capacity. Specified capacity
StringBuffer(String str) Creates a StringBuffer containing the specified initial string. str.length() + 16
StringBuffer(CharSequence seq) Creates a StringBuffer containing the specified character sequence. seq.length() + 16

Capacity & Capacity Expansion Formula

When the content added to a StringBuffer exceeds its current capacity, Java automatically reallocates memory using the following growth formula:

New Capacity = (Old Capacity * 2) + 2

Capacity Calculation Example:

public class StringBufferCapacityDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); // Default initial capacity = 16 System.out.println("Initial Capacity: " + sb.capacity()); // 16 sb.append("Hello World Java!"); // 17 characters added System.out.println("New Capacity: " + sb.capacity()); // (16 * 2) + 2 = 34 } }

Comprehensive Guide to StringBuffer Methods

Below is a detailed breakdown of all fundamental StringBuffer methods, accompanied by explanations and execution examples.

1. append() Method

Appends the string representation of any data type (int, char, float, String, Object) to the end of the existing buffer sequence.

public class AppendDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Java"); sb.append(" Programming"); sb.append(" "); sb.append(2026); System.out.println(sb); } }
Output:

Java Programming 2026

2. insert() Method

Inserts text or data at a specified index offset without overwriting existing character data.

public class InsertDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Core "); sb.insert(5, "Java"); System.out.println(sb); } }
Output:

Core Java

3. replace() Method

Replaces characters within a range specified by start index (inclusive) and end index (exclusive) with a given string.

public class ReplaceDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello World"); sb.replace(6, 11, "Java"); System.out.println(sb); } }
Output:

Hello Java

4. delete() and deleteCharAt() Methods

delete(int start, int end) removes a sequence of characters, while deleteCharAt(int index) removes a single character at the specified index position.

public class DeleteDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Roadmap For Java"); // Deletes " For" (from index 7 to 11) sb.delete(7, 11); System.out.println("After delete(): " + sb); // Deletes 'a' at index 0 sb.deleteCharAt(0); System.out.println("After deleteCharAt(): " + sb); } }
Output:

After delete(): Roadmap Java
After deleteCharAt(): oadmap Java

5. reverse() Method

Reverses the sequence of characters in the buffer in place.

public class ReverseDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Java"); sb.reverse(); System.out.println(sb); } }
Output:

avaJ

6. capacity() and ensureCapacity() Methods

capacity() returns the current total character capacity allocated. ensureCapacity(int minimumCapacity) guarantees that the total capacity allocated is at least equal to the specified minimum.

public class EnsureCapacityDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer(); System.out.println("Default: " + sb.capacity()); // 16 sb.ensureCapacity(50); System.out.println("Ensured Capacity: " + sb.capacity()); // 50 } }
Output:

Default: 16
Ensured Capacity: 50

7. setLength() and trimToSize() Methods

setLength(int newLength) forces the character sequence length to a specific size. trimToSize() reduces memory storage overhead by shrinking the buffer capacity down to fit the current character length exactly.

public class LengthAndTrimDemo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Roadmap"); System.out.println("Initial Capacity: " + sb.capacity()); // 7 + 16 = 23 sb.trimToSize(); System.out.println("Trimmed Capacity: " + sb.capacity()); // 7 } }
Output:

Initial Capacity: 23
Trimmed Capacity: 7

How Strings Are Compared: String vs StringBuffer (Critical Difference)

Comparing String objects and StringBuffer objects works very differently in Java because of how each class overrides (or does not override) Object methods.

1. String Comparison (`equals()`)

The String class **overrides** Object.equals() to perform a **content-based comparison**.

  • s1.equals(s2) checks if the characters inside both Strings match, position by position.

2. StringBuffer Comparison (`equals()`)

The StringBuffer class **DOES NOT override** Object.equals()!

  • When you call sb1.equals(sb2) on two StringBuffer instances, it performs a **reference/address comparison** (behaves exactly like the == operator).
  • Even if two StringBuffer objects contain identical text (e.g., "Java"), calling .equals() on them returns false unless both reference variables point to the exact same object memory location!
How to Compare Contents of Two StringBuffer Objects:

To compare the actual text contained inside two StringBuffer objects, you must first convert them to String using toString() or compare them using compareTo().

Code Example: String vs StringBuffer Comparison

public class ComparisonTrapDemo { public static void main(String[] args) { // --- STRING COMPARISON --- String str1 = new String("Java"); String str2 = new String("Java"); System.out.println("String == : " + (str1 == str2)); // false (different objects) System.out.println("String equals(): " + str1.equals(str2)); // true (content matches) System.out.println("----------------------------------"); // --- STRINGBUFFER COMPARISON --- StringBuffer sb1 = new StringBuffer("Java"); StringBuffer sb2 = new StringBuffer("Java"); System.out.println("StringBuffer == : " + (sb1 == sb2)); // false (different objects) System.out.println("StringBuffer equals(): " + sb1.equals(sb2)); // FALSE! (Inherited Object.equals - address comparison) // --- CORRECT WAY TO COMPARE STRINGBUFFERS --- boolean contentMatch = sb1.toString().equals(sb2.toString()); System.out.println("StringBuffer toString().equals(): " + contentMatch); // true } }
Output:

String == : false
String equals(): true
----------------------------------
StringBuffer == : false
StringBuffer equals(): false
StringBuffer toString().equals(): true
Interview Question:

Q: What is the output of new StringBuffer("Test").equals(new StringBuffer("Test"))?

A: It returns false because StringBuffer inherits the default equals() method from Object class, which compares memory references, not the string content.


What is StringBuilder in Java?

The StringBuilder class was introduced in Java 5 as a high-performance alternative to StringBuffer. Like StringBuffer, it represents a mutable sequence of characters. However, StringBuilder is **non-synchronized**, making it faster when thread safety is not required.

Key Characteristics of StringBuilder:

  • ✔ Mutable: Allows character modifications directly in memory without creating new intermediate objects.
  • ✔ Not Thread-Safe: Methods are not synchronized, making it unsuitable for multi-threaded access without external synchronization.
  • ✔ High Performance: Executes faster than StringBuffer because it avoids synchronization overhead.
  • ✔ Identical API: Shares the exact same core methods (append(), insert(), replace(), delete(), reverse()) as StringBuffer.

StringBuilder Code Example

public class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Roadmap"); sb.append(" For"); sb.append(" Java"); System.out.println("Modified StringBuilder: " + sb); sb.reverse(); System.out.println("Reversed StringBuilder: " + sb); } }
Output:

Modified StringBuilder: Roadmap For Java
Reversed StringBuilder: avaJ roF pamdaoR

Master Comparison: String vs StringBuffer vs StringBuilder

Here is a complete comparison breakdown across all three core character classes in Java:

Feature String StringBuffer StringBuilder
Mutability Immutable (Cannot be changed) Mutable (Can be changed) Mutable (Can be changed)
Thread Safety Thread-Safe (Immutable) Thread-Safe (Synchronized) Not Thread-Safe (Non-synchronized)
Performance Slow for frequent edits Slower than StringBuilder Fastest execution speed
Memory Location String Constant Pool / Heap Heap Memory Heap Memory
Storage Mechanism Constant value representation Dynamic expandable array buffer Dynamic expandable array buffer
Introduced In Java 1.0 Java 1.0 Java 1.5
Best Use Case Fixed text, constant strings, keys Multi-threaded modifications Single-threaded heavy modifications

Top String Interview Questions Checklist

  1. What is the difference between String, StringBuffer, and StringBuilder?
  2. Why are String objects made immutable in Java?
  3. What is the String Constant Pool (SCP) and where is it located in Java memory?
  4. How many objects are created when executing String s = new String("Hello");?
  5. What is the difference between == operator and .equals() method?
  6. What is the default capacity of StringBuffer and how does its capacity growth formula work?

Continue Your Java Journey

Congratulations! You have completed the complete guide on Strings in Java.

Next Topic: Object-Oriented Programming (OOPs) Concepts in Java

Explore More Java Tutorials

Comments

Popular posts from this blog

Java Roadmap

Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-2)

Identifiers