String
achieves memory management in Java.
String name = "Deepak";
"Deepak"
is stored in the String Constant Pool.
name
will point to the already existing object.
new
Keyword:
String name = new String("Amit");
new
keyword."Amit"
does not already exist.name
points to the Heap object, not the SCP object.
String s = "Java";
, the literal "Java"
is placed in this pool.
String s1 = "Hello";
String s2 = "Hello"; // s2 points to the same object as s1
System.out.println(s1 == s2); // true
new
Keyword:
new
, the object is created in the heap (outside SCP) and not reused.
String s1 = new String("World");
String s2 = new String("World");
System.out.println(s1 == s2); // false (different objects in heap)
intern()
method in SCP:
intern()
method in Java is used for memory optimization.
String s1 = new String("Hello"); // Created in Heap
String s2 = s1.intern(); // Returns reference from String Pool (SCP)
String s3 = "Hello"; // Literal in String Pool (SCP)
System.out.println(s1 == s2); // false (s1 is from Heap, s2 from SCP)
System.out.println(s2 == s3); // true (both s2 and s3 are from SCP)
intern()
will return the same reference to that string, instead of creating a new one.
intern()
, you can compare strings with the ==
operator. This works because both strings that are interned point to the same object in the string pool.
intern()
method works because strings in Java are immutable. This means their values can't be changed once created, so they can safely be shared between multiple parts of a program. However, mutable objects can't be shared like this, as their content can change.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.