Core Java Fundamentals ยท Strings & Objects
A deep dive into how Java strings are created, stored in memory, and why they are immutable.
public class StringDemo {
public static void main(String[] args) {
// Part 1: String Creation
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
System.out.println("--- Creation & Comparison ---");
System.out.println("s1 == s2: " + (s1 == s2));
System.out.println("s1 == s3: " + (s1 == s3));
System.out.println("s1.equals(s3): " + s1.equals(s3));
// Part 2: Immutability
String s4 = "Hello";
System.out.println("\n--- Immutability ---");
s4.concat(" World");
System.out.println("s4 after concat (no assignment): " + s4);
s4 = s4.concat(" World");
System.out.println("s4 after concat (with assignment): " + s4);
}
}s1 and assign it a string literal "Java". The JVM checks the String Constant Pool (SCP). Since "Java" is not there, it gets created in the SCP, and s1 now refers to it.s2 and assign it the same literal "Java". The JVM checks the SCP, finds "Java" already exists, and makes s2 refer to the *same* memory location as s1. No new string is created.new keyword. This forces the JVM to create a new String object on the Heap, even though "Java" is already in the SCP. So, s3 refers to a completely different object than s1 and s2.== operator compares memory ides (references). Since s1 and s2 point to the exact same object in the SCP, this evaluates to true.s1 (in SCP) with s3 (in Heap). Since they are two different objects in different memory locations, the == operator returns false..equals() method compares the actual character sequence of the strings. Since both s1 and s3 contain "Java", this returns true. This is the correct way to compare string content.s4 with the value "Hello". This demonstrates the concept of immutability.s4.concat(" World") creates a brand new string "Hello World" in memory, but the result is not assigned to any variable. The original string s4 remains unchanged.s4, we see its value is still "Hello", proving that the previous concat operation did not modify s4.s4, we must re-assign the result of the concat operation back to s4. Now, s4 points to the new "Hello World" string object.s4 again. This time it shows the new value "Hello World" because its reference was updated in the previous step.