Strings in Java & String Methods with Immutable Nature
Strings are one of the most commonly used data types in Java. They allow you to store and manipulate sequences of characters, such as names, messages, or any text data. Understanding strings and their methods is crucial for writing efficient Java programs.
Strings are one of the most commonly used data types in Java. They allow you to store and manipulate sequences of characters, such as names, messages, or any text data.
What is a String in Java?
- A String in Java is an object that represents a sequence of characters.
- Strings are immutable, meaning once created, their value cannot be changed.
- Strings belong to the
java.langpackage, so you don’t need to import anything to use them.
Example:
String name = "John";
System.out.println("Name: " + name);
Output:
Name: John
String Declaration and Initialization
There are two main ways to create strings:

- Using String Literal
String message = "Hello Java";
- Using
newKeyword
String message = new String("Hello Java");
Note : String literals are stored in the String Pool to save memory. Using new creates a new object in the heap every time.
String Characteristics
| Feature | Description |
|---|---|
| Immutable | Strings cannot be modified after creation |
| Indexed | Characters in a string are indexed from 0 |
| Object | Strings are objects, not primitive data types |
| Methods | Strings have many built-in methods for manipulation |
Common String Methods
| Method | Description | Example |
|---|---|---|
length() | Returns the number of characters | "Java".length() → 4 |
charAt(int index) | Returns character at specified index | "Java".charAt(2) → 'v' |
concat(String s) | Concatenates another string | "Java".concat(" Programming") → "Java Programming" |
toUpperCase() | Converts to uppercase | "java".toUpperCase() → "JAVA" |
toLowerCase() | Converts to lowercase | "JAVA".toLowerCase() → "java" |
equals(String s) | Compares two strings | "Java".equals("java") → false |
equalsIgnoreCase(String s) | Compares ignoring case | "Java".equalsIgnoreCase("java") → true |
substring(int start, int end) | Extracts substring | "Java".substring(1,3) → "av" |
trim() | Removes leading and trailing spaces | " Java ".trim() → "Java" |
replace(char old, char new) | Replaces character | "Java".replace('a','o') → "Jovo" |
Immutable Nature of Strings
- Immutable: Once a string is created, it cannot be modified.
- Any operation on a string returns a new string object.
Example:
String str = "Java";
String newStr = str.concat(" Programming");
System.out.println(str); // Java
System.out.println(newStr); // Java Programming
Why Strings Are Immutable
- Security: Strings are used in sensitive operations (e.g., passwords, file paths).
- Thread-Safety: Immutable objects can be shared safely in multithreaded environments.
- Memory Efficiency: String Pool reuses immutable objects.
- Performance: Cached hashcode improves performance in collections like
HashMap.
String Pool in Java
- The String Pool is a special memory area for storing string literals.
- Strings created using literals go into the pool.
- Strings created with
newdo not go into the pool (stored in heap).
Example:
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println(s1 == s2); // true, same object in pool
System.out.println(s1 == s3); // false, different objects
Practical Example
public class StringExample {
public static void main(String[] args) {
String firstName = "John";
String lastName = "Doe";
// Concatenation
String fullName = firstName + " " + lastName;
System.out.println("Full Name: " + fullName);
// Length
System.out.println("Length: " + fullName.length());
// Substring
System.out.println("First Name: " + fullName.substring(0, 4));
// Uppercase
System.out.println("Uppercase: " + fullName.toUpperCase());
}
}
Output:
Full Name: John Doe
Length: 8
First Name: John
Uppercase: JOHN DOE
🏆 Top 5 Java Interview Questions - Java Strings & Methods
1. What is the difference between String, StringBuilder, and StringBuffer?
Answer:
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutability | Immutable | Mutable | Mutable |
| Thread Safety | Not thread-safe (immutable by default) | Not synchronized, not thread-safe | Synchronized, thread-safe |
| Performance | Slower for concatenation | Faster for concatenation | Slightly slower than StringBuilder |
| Usage | Store fixed strings | Efficient string modifications in a single thread | Efficient string modifications in multi-threaded environment |
Example:
String str = "Hello"; // immutable
StringBuilder sb = new StringBuilder("Hello"); // mutable
StringBuffer sbf = new StringBuffer("Hello"); // thread-safe
2. Why are strings immutable in Java?
Answer:
- To improve security (e.g., for class loading, network connections).
- To enable string sharing via the String Pool, saving memory.
- To make thread-safe operations without explicit synchronization.
- To allow hashCode caching for faster operations in collections like
HashMap.
3. What is the String Pool?
Answer:
- A special memory region in Heap where String literals are stored.
- Strings in the pool are shared; duplicate literals point to the same object.
- Helps reduce memory usage and improves performance.
Example:
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2); // true (same object in String Pool)
String s3 = new String("Java");
System.out.println(s1 == s3); // false (new object in Heap)
4. Difference between == and equals() for strings?
Answer:
==→ Compares reference (memory address).equals()→ Compares content/value of the string.
Example:
String a = "Hello";
String b = new String("Hello");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
5. How do you concatenate strings in Java efficiently?
Answer:
- For few concatenations,
+operator is fine. - For multiple concatenations in loops, use
StringBuilderorStringBufferto avoid creating multiple immutable objects.
Example:
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 5; i++) {
sb.append(i).append(" ");
}
System.out.println(sb.toString()); // 0 1 2 3 4
