Features of the String
Class in Java
The String
class in Java is one of the most commonly used classes and provides several important features.
1. Strings are Immutable
- Once a
String
object is created, its value cannot be changed. - Any modification (e.g., concatenation, substring) creates a new
String
object instead of modifying the existing one.
Example:
public class StringImmutable {
public static void main(String[] args) {
String str = "Hello";
str.concat(" World"); // Creates a new String, but doesn't change `str`
System.out.println(str); // Output: Hello (original string remains unchanged)
str = str.concat(" World"); // Now `str` points to a new object
System.out.println(str); // Output: Hello World
}
}
👉 Why? concat(" World")
creates a new string instead of modifying str
.
2. Stored in the String Pool (String Interning)
- String literals are stored in a special memory area called the String Pool.
- If a string with the same value already exists in the pool, Java reuses the existing string instead of creating a new one.
Example:
public class StringPoolExample {
public static void main(String[] args) {
String s1 = "Java"; // Stored in String Pool
String s2 = "Java"; // Points to the same object in the pool
System.out.println(s1 == s2); // true (same reference)
}
}
👉 Strings created with new String("Java")
are NOT stored in the pool unless explicitly interned.
String s3 = new String("Java"); // Created in Heap
System.out.println(s1 == s3); // false (different objects)
s3 = s3.intern(); // Now refers to the String Pool object
System.out.println(s1 == s3); // true (same reference after interning)
3. String
is Final and Implements CharSequence
- The
String
class is declared asfinal
, meaning it cannot be subclassed. - It implements the
CharSequence
,Comparable<String>
, andSerializable
interfaces.
public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
// Internal implementation
}
👉 Why is String
final?
- Security: Prevents modification of string contents (useful in class loading, network connections, etc.).
- Performance: Helps in efficient string interning.
- Thread Safety: Since strings are immutable, multiple threads can safely share them.
4. Supports String Manipulation Methods
The String
class provides many built-in methods for working with strings.
Common String Methods
Method | Description | Example |
---|---|---|
length() | Returns the number of characters | "Hello".length(); // 5 |
charAt(index) | Returns character at given index | "Java".charAt(1); // 'a' |
substring(start, end) | Extracts part of a string | "Hello".substring(1, 4); // "ell" |
indexOf("str") | Returns the first occurrence of a substring | "Hello".indexOf("l"); // 2 |
contains("str") | Checks if string contains another string | "Java".contains("av"); // true |
toLowerCase() | Converts to lowercase | "HELLO".toLowerCase(); // "hello" |
toUpperCase() | Converts to uppercase | "hello".toUpperCase(); // "HELLO" |
trim() | Removes leading and trailing spaces | " hello ".trim(); // "hello" |
replace("a", "b") | Replaces occurrences of a character | "banana".replace("a", "o"); // "bonono" |
split(" ") | Splits the string into an array | "a,b,c".split(","); // ["a", "b", "c"] |
5. Supports String Concatenation
- Strings can be concatenated using
+
orconcat()
. - The
+
operator is optimized using theStringBuilder
internally.
Example:
public class StringConcat {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // Uses StringBuilder internally
System.out.println(result); // Output: Hello World
}
}
👉 For performance-critical operations, use StringBuilder
instead of String
for multiple concatenations.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // Output: Hello World
6. String
is Thread-Safe
- Since
String
is immutable, it is thread-safe by design. - Multiple threads can access the same string without synchronization issues.
7. Can Be Converted to Other Types
- You can convert strings to numbers using wrapper classes (
Integer
,Double
, etc.). - The
valueOf()
method is used for safe conversions.
int num = Integer.parseInt("123"); // Converts "123" to int
double d = Double.valueOf("3.14"); // Converts "3.14" to double
8. String Comparison (==
vs. .equals()
)
==
compares references, not content..equals()
compares actual string values.
Example:
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
👉 Always use .equals()
to compare string values.
9. String Formatting (String.format()
)
- You can format strings dynamically using
String.format()
.
String name = "John";
int age = 30;
String formatted = String.format("Name: %s, Age: %d", name, age);
System.out.println(formatted); // Output: Name: John, Age: 30
10. String Joining (String.join()
)
- You can join multiple strings using
String.join()
.
String joined = String.join(", ", "Apple", "Banana", "Cherry");
System.out.println(joined); // Output: Apple, Banana, Cherry
Summary of Key Features
Feature | Description |
---|---|
Immutable | Strings cannot be modified after creation. |
Stored in String Pool | String literals are stored in a shared pool to save memory. |
Final Class | Cannot be subclassed, ensuring security and efficiency. |
Many Built-in Methods | Supports operations like substring() , replace() , split() , etc. |
Supports Concatenation | Can be combined using + or concat() . |
Thread-Safe | Since strings |