Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

java - What happens when assigned null to String object?

I am trying to understand what happens to a string when null is assigned to it. So, I have a String str = new String("abc"); It uses some space in memory. When str is assigned null, i.e str = null, what happens to the memory that was used to create "abc" . Does it still use space in memory?

question from:https://stackoverflow.com/questions/65907775/what-happens-when-assigned-null-to-string-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java is garbage collected. The memory allocated for the string will be freed at a feature point in time determined by the garbage collector. See Java Garbage Collection Basics for details.

Update: as commenters pointed out string interning might prevent the string from getting garbage collected. Details depend on many things like the scope of the reference, JVM and Java version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...