0

I understand that strings (at least in Java) are immutable. I'm not trying to empty the contents of the string.

If I did, I'd use this: output.setText( outputString );

My question is: if you wanted to minimize the amount of space a program requires by relinquishing the bits storing the string, is there a way to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

5

In Java, garbage collection is done by JVM. So the answer to your question is no.

At best you can make the object eligible for garbage collection by making sure that the Object is not referenced anywhere.One way is to make any variable reference as null which is referring the object in question and calling System.gc().

String outputString ="Some Value";
outputString =null

The object "Some Value" in heap memory is not being referenced from anywhere and becomes eligible for garbage collection.

System.gc() hints the JVM to do garbage collection. There is no guarantee that the object will be freed from heap memory.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
0

There is an automated garbage collector in Java.

In Java, as the developer does not explicitly remove the memory in the program code, the garbage collector finds the unnecessary (garbage) objects and removes them.

http://www.cubrid.org/blog/dev-platform/understanding-java-garbage-collection/

GreySwordz
  • 368
  • 1
  • 9