0
String str1 = "Test";
final String str2 = new String("Test");

As we know, the str1 will be created in String pool and str2 will be created in Heap. Here, both objects are immutable. Is there any difference in performance(while performing GC)? Is it correct to say creating String objects in Heap leads to memory leak?

1
  • Java doesn't get true memory leaks, in the sense that a C or C++ developer would understand it. You can have collections retain objects which are no longer useful, but you can't have memory which can never be recovered. Commented Apr 2, 2012 at 13:30

3 Answers 3

8

Is it correct to say creating String objects in Heap leads to memory leak?

No. When there are no references to the object, it will be eligible for garbage collection, just like any other object.

Sign up to request clarification or add additional context in comments.

Comments

2

No, String objects in the heap don't lead to memory leaks. They can be garbage collected just like regular objects.

However, you might be using a lot of memory to hold string objects that are identical in content. Holding 1 million references to the same object is more memory-efficient than creating 1 million different objects.

Note that you can use the intern function to add a string obtained at runtime to the String pool.

public class Test {
   public static void main(String[] args) {
      new Test().run();
   }

   private void run() {
      String str1 = "Test";
      String str2 = "Test";
      System.out.println(str1 == str2);

      String str3 = new String("Test");
      String str4 = new String("Test");
      System.out.println(str3 == str4);

      String str5 = str3.intern();
      String str6 = str3.intern();
      System.out.println(str5 == str6);
   }
}

Output:

true
false
true

Comments

0

Althought true that string objects are stored on the heap and will be garbage collected, I have run into issues in that the JVM holds onto the references. Check out javolution, it is a real time library that can help you optimize your code for high throughput. in hindsight, I would have chosen a different language then java because of all the issues we ran into, but here it is:

http://javolution.org/

1 Comment

String literals are held internally in the String class's string pool, and as such won't be eligible for garbage collection. Other String objects should be no different to any other object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.