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.
What is a String?
A String is simply a sequence of characters.
In Java, anything enclosed within double quotes (" ") is treated as a String.
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.
- 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 Area | Example |
|---|---|
| User Name | "Ravi" |
| Password | "Admin@123" |
| "abc@gmail.com" | |
| File Name | "report.pdf" |
| City | "Hyderabad" |
| JSON Data | "name":"John" |
| Database Values | "Employee" |
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.
Notice the keyword final. Since the String class is declared as final, it cannot be inherited.
Is String a primitive data type?
Answer: No. String is a predefined final class available in the java.lang package.Basic String Declaration
Here,
- String → Class name
- s → Reference variable
- "Java" → String literal
| char | String |
|---|---|
| 'A' | "A" |
| Stores one character | Stores multiple characters |
| Primitive datatype | Object |
| Uses single quotes | Uses double quotes |
Example Program
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:
- Using a String Literal (e.g.,
String s = "Java";) - Using the
newKeyword (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.
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.
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
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.s2points to the same object ass1.- Total Objects Created: 1 Object (in SCP).
Example 2: Using new Keyword
Analysis:
- 1 Object created in the Heap Memory because of the
newkeyword. - 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
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
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
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 + s2involves variables, so it is evaluated at runtime usingStringBuilder. 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.
- 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
String Value: Roadmap
To capture the modified value, you must assign the return result to a variable:
4 Key Reasons Why Strings Are Made Immutable
-
String Pool Optimization: Sharing pooled literal references would be dangerous if Strings were mutable. If variable
Achanged its value, variableBpointing to the same pooled reference would get modified unintentionally! - 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.
- 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.
-
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 likeHashMapandHashSet.
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 Signature | Description |
|---|---|
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
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:
| Method | Return Type | Description |
|---|---|---|
charAt(int index) | char | Returns the character at the specified index. |
length() | int | Returns the total length of the string. |
concat(String str) | String | Appends specified string to the end. |
contains(CharSequence s) | boolean | Returns true if sequence exists in string. |
startsWith(String prefix) | boolean | Checks if string starts with given prefix. |
endsWith(String suffix) | boolean | Checks if string ends with given suffix. |
equals(Object anObject) | boolean | Compares content equality. |
equalsIgnoreCase(String anotherString) | boolean | Compares content ignoring case. |
indexOf(String str) | int | Returns index of first occurrence of substring. |
lastIndexOf(String str) | int | Returns index of last occurrence of substring. |
isEmpty() | boolean | Returns true if length is 0. |
isBlank() (Java 11+) | boolean | Returns true if string is empty or contains only whitespace. |
replace(char old, char new) | String | Replaces old characters with new characters. |
replaceAll(String regex, String replacement) | String | Replaces matches of regex with replacement. |
split(String regex) | String[] | Splits string into array around regex matches. |
substring(int beginIndex) | String | Extracts substring from index to end. |
substring(int begin, int end) | String | Extracts substring from begin to end index. |
toLowerCase() / toUpperCase() | String | Converts casing of character contents. |
trim() / strip() | String | Removes 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.
2. String Comparison Methods
Use equals(), equalsIgnoreCase(), and compareTo() for value checking.
3. Search, Replace & Splitting Methods
Search using contains() or indexOf(), replace text using replace(), or tokenize strings using split().
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
StringBufferare synchronized, making it safe for access by multiple threads concurrently. - ✔ Stored in Heap Memory:
StringBufferobjects 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.
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:
| Constructor | Description | Initial 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:
Capacity Calculation Example:
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.
Java Programming 2026
2. insert() Method
Inserts text or data at a specified index offset without overwriting existing character data.
Core Java
3. replace() Method
Replaces characters within a range specified by start index (inclusive) and end index (exclusive) with a given string.
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.
After delete(): Roadmap Java
After deleteCharAt(): oadmap Java
5. reverse() Method
Reverses the sequence of characters in the buffer in place.
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.
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.
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 twoStringBufferinstances, it performs a **reference/address comparison** (behaves exactly like the==operator). - Even if two
StringBufferobjects contain identical text (e.g.,"Java"), calling.equals()on them returnsfalseunless both reference variables point to the exact same object memory location!
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
String == : false
String equals(): true
----------------------------------
StringBuffer == : false
StringBuffer equals(): false
StringBuffer toString().equals(): true
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
StringBufferbecause it avoids synchronization overhead. - ✔ Identical API: Shares the exact same core methods (
append(),insert(),replace(),delete(),reverse()) asStringBuffer.
StringBuilder Code Example
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
- What is the difference between String, StringBuffer, and StringBuilder?
- Why are String objects made immutable in Java?
- What is the String Constant Pool (SCP) and where is it located in Java memory?
- How many objects are created when executing
String s = new String("Hello");? - What is the difference between
==operator and.equals()method? - 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
Post a Comment