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?
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.
Output: