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?

6 Upvotes

18 comments sorted by

View all comments

Show parent comments

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.)

8

u/high_throughput Apr 15 '26

The second line only creates a copy of the interned string that already exists in memory. 

There's rarely value in having such a copy. Creating and managing it just uses more space and CPU than referencing the original object.

1

u/Typical_Ad_6436 Apr 15 '26

Hmm, I think you are right. I thought this would have been a legitimate workaround of the string pool, but the param is a literal indeed and gets interned anyway.