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