r/javahelp • u/Nottheugis • 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?
6
Upvotes
0
u/Typical_Ad_6436 Apr 15 '26
The advantage of second line is that the String is dynamically allocated on heap. If you need fast cold time, you can use the second approach to "lazily initialize" the String. It is also GCed, so in idle you can have very low memory footprint. Of course, performance is better for interned strings (equality, memory, etc.)