1

In order to make my code more readable, I decided to create a String, and then to use it inside an "algorithm" (similar to the following):

JsonArray users = import();
String currentUser = db.getName(currentID);
for (int i=0; i < users.size(); i++) {
    user = (JsonObject) users.get(i);
    if (user.get("username").getAsString().equals(currentUser)) {
        System.out.println("The user's index is " + i);
    }
}
currentUser = null;  // This line raises the warning

When the "algorithm" is done, I want to delete the String - and therefore I assign it null (after reading this). However IntelliJ doesn't seem to like it, because it raises the obvious warning:

The value null assigned to 'currentUser' is never used (...)

Is there a better way to delete objects that I'm missing, or is it just a bug that I can ignore?

GalAbra
  • 5,048
  • 4
  • 23
  • 42
  • Do you have an actual memory problem? Smells like premature optimization. It definitely doesn't improve readability. – shmosel Jan 04 '18 at 03:38
  • Does `currentUser` go out of scope? If so, `null`ing it is a waste of time. If not, then it's debatable. So, does it? – Elliott Frisch Jan 04 '18 at 03:39
  • 1
    Objects are automatically eligible for garbage collection when they are no longer reachable. If you really have to use mechanisms like this to keep your memory usage down, it is very likely that there are serious problems with the design of your code. – Robby Cornelissen Jan 04 '18 at 03:39
  • Thank you for your replies. After experiencing C++ I wanted to test the concept of memory deallocation in Java, so I read the article I've linked to and thought it could be beneficial for my code. From your comments, I get the feeling that it's just completely unnecessary in Java and therefore IntelliJ doesn't recognize it as a legitimate code – GalAbra Jan 04 '18 at 03:45
  • 1
    You don't have to assign nulls to Objects manually that's what GC is there for, the only time you need to assign null yourself would be if the class you're working with is responsible for managing it's own memory. – whatamidoingwithmylife Jan 04 '18 at 04:11

0 Answers0