String Class Characteristics and String Comparison in Java
String Class Characteristics
String Instantiation
String str = "example";
String str = new String("example");
Java maintains a String Pool, also known as the string constant pool, which stores unique string literals generated during runtime. Unlike regular objects that reside solely in heap memory, strings in this pool avoid duplication.
When a String is instantiated via direct assignment, its content is placed into the string pool if not already present. Subsequent direct assignments referencing the same string will retrieve it from the pool, reusing the existing object rather than allocating new memory.
The first method above stores the string directly in the pool. The second creates a new String object in heap memory, resulting in a distinct memory address and object instance.
String Anonymous Objects
A string literal enclosed in double quotes, such as "example", is inherently a String anonymous object.
String Operations
String cnocatenation with other data types always yields a String result. For instance:
String s3 = "abc" + "d";
String s4 = s3 + 5; // Results in "abcd5"
String Comparison
-
The
==operator checks if two references point to the same object in memory, comparing addressses. It returnstrueonly if they are identical objects. -
The
equals(Object anObject)method compares the content of strings for equality, as the String class overrides this method.
Example:
String s1 = new String("abc");
String s2 = "abc";
s1 == s2; // false
s1.equals(s2); // true
Demonstration code:
public class StringComparisonDemo {
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = "abc";
String s3 = new String("abc");
String s4 = "ab" + "c";
String suffix = "c";
String s5 = "ab" + suffix;
System.out.println("--- Reference Comparisons ---");
System.out.println(s1 == s2); // false
System.out.println(s1 == s3); // false
System.out.println(s2 == s3); // false
System.out.println(s2 == s4); // true
System.out.println(s2 == s5); // false
}
}
Strings are immutable; their content cannot be altered after creation. Operations like += create new String objects, leaving the original unchanged.
Interview Question: String Instantiation Differences
- Direct Assignment: Allocates a single heap memory slot, employs a shared design pattern, automatically pools the string, and facilitates reuse.
- Constructor Method: Creates two memory segments (one potentially becoming garbage), does not auto-pool the string, though
intern()can manually pool it.
For development, direct assignment is generally preferred due to its efficiency and automatic pooling.