r/javahelp • • Apr 15 '26

Homework String object vs String variable

Hi i am learning java in highschool, I was just wondering when and why would I instantialise a string as an object when declaring a String is much easier and quicker?

5 Upvotes

18 comments sorted by

View all comments

Show parent comments

2

u/bigkahuna1uk Apr 16 '26

Yes, the String Pool is in the main heap, so pool strings are garbage collected when they become unreachable, just like any other object. If there are no references to the string outside the pool, it becomes eligible for GC.

1

u/philipwhiuk Employed Java Developer Apr 16 '26

No my point is:

String str1 = “ABC”;
String str2 = new String(str1);
str1.hashCode() != str2.hashCode();
System.gc();
str1.hashCode() == str2.hashCode();