0

The nature of a String in Java is immutable, therefore, a new value attribution for a existent variable will result in a new String. Saying that, can I null or zero that old String?

I'm asking because there's no guarantee the Garbage Collector will clean up even if I call it, at the time I want.

The point here is security: a String in memory could be retrieved in a compromised device, right?

TylerH
  • 20,799
  • 66
  • 75
  • 101
ramires.cabral
  • 910
  • 4
  • 13
  • 28
  • 1
    A common solution to this problem is to use a `char[]` rather than a string. Then you fill it with spaces as soon as you've finished with it and you don't need to care when it gets garbage collected. – cpp beginner Dec 29 '16 at 15:58
  • @cppbeginner For cases where you can use a char[] instead a String. In an EditText, for instance, it's not possible... – ramires.cabral Dec 29 '16 at 16:03
  • 1
    May be of interest: http://www.javacreed.com/how-to-modify-a-string-without-creating-a-new-one/ – Patrick Parker Dec 29 '16 at 16:07
  • 1
    I don't know if this answer is correct, but it's definitely relevant. http://stackoverflow.com/a/15844273/6253321 – cpp beginner Dec 29 '16 at 16:08
  • @PatrickParker Very interesting reading. Worth it! – ramires.cabral Dec 29 '16 at 16:20
  • @cppbeginner A fast search in EditText source code which extends TextView reveals that getText() method returns mText and mText is initialized in TextView constructor as mText = ""; – ramires.cabral Dec 29 '16 at 16:29

1 Answers1

2

can I null or zeroing that old String?

No.

A String in memory could be retrieved in a compromised device, right?

Yes, but it would require a rooted device or a combination of the SDK tools and direct access to the device.

You need to decide whether your threat vectors include people who would go to those extremes.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491