In Java, a String is an object that encapsulates an immutable sequence of characters. Unlike C/C++ where strings are simple null-terminated character arrays, Java treats strings as first-class objects defined in the java.lang.String class.
Figure 7: Memory Model of String Literals inside the SCP vs new String() Heap Objects.
new String()String s = "Java";): Stored in the String Constant Pool (SCP). If "Java" already exists in the pool, no new object is created; the existing reference address is shared.new Keyword (String s = new String("Java");): Forces the JVM to allocate a brand-new object in the general Heap memory, outside the SCP pool, even if the literal already exists.== Operator vs. .equals() Methodpublic class StringComparisonDemo {
public static void main(String[] args) {
String s1 = "Veewom";
String s2 = "Veewom";
String s3 = new String("Veewom");
// 1. Reference comparison (==):
System.out.println("s1 == s2: " + (s1 == s2)); // true (Both point to same SCP address!)
System.out.println("s1 == s3: " + (s1 == s3)); // false (s3 points to separate Heap address!)
// 2. Content comparison (.equals()):
System.out.println("s1.equals(s3): " + s1.equals(s3)); // true (Identical characters!)
// 3. The .intern() method:
String s4 = s3.intern(); // Fetches reference from SCP pool
System.out.println("s1 == s4: " + (s1 == s4)); // true!
}
}
| Method | Description | Example (s = "Hello World") |
|---|---|---|
length() | Returns character count | s.length() → 11 |
charAt(index) | Returns char at specified index | s.charAt(0) → 'H' |
substring(begin, end) | Extracts substring (end exclusive) | s.substring(0, 5) → "Hello" |
contains(seq) | Checks if substring exists | s.contains("World") → true |
toUpperCase() | Converts to all uppercase | s.toUpperCase() → "HELLO WORLD" |
trim() / strip() | Removes leading/trailing whitespace | " Hi ".strip() → "Hi" |
split(regex) | Splits string into array by delimiter | s.split(" ") → ["Hello", "World"] |
Frequent Exam Question: "How many objects are created in memory by: String s = new String("Java");?"
Answer: Two objects! (Assuming "Java" is not already in the pool):
1. One object is created in the String Constant Pool (SCP) for the literal parameter "Java".
2. A second distinct object is created in the general Heap memory by the new operator.
The variable s points to the object in general Heap memory.
Because String is immutable, repeated concatenation in loops creates massive garbage. Let us explore mutable StringBuilder and StringBuffer. Proceed to: StringBuilder vs StringBuffer →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Mutable string alternatives.
Pattern matching with strings.
Converting strings to primitives.
Heap allocation details.