Thedudxo
Thedudxo

Reputation: 591

should i set variable to null when user exits

I'm creating a text based game to further my knowledge with java.

The user uses their keyboard to interact with the game, and while in the main menu can press "2" to quit the game.

if(userInput.equals("2")){
            playing = false;

The playing variable defines whether the game loop should continue running or not.

I also have a variable named mode which defines which state the game is in, for example, the main menu, options, or the actual game.

Should i change mode to "null" (or similar) when i set playing = false?

I't doesn't matter very much to my overall program, but since I am new to java i would like to know what the best practices are for these kinds of things.

Upvotes: 1

Views: 85

Answers (2)

Vitaly
Vitaly

Reputation: 2662

If you do not need it more -- yes. But I think better way is hold all data belong to player in one class. And release reference to object of this class (set to null) when user left your program.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

If pressing 2 closes the program (shutting down the JVM), then it doesn't make much of a difference. Actually you will have an additional instruction to push the null reference onto the stack.

If you have quite a lot of code (the term lot is relative), then you can set the reference to null so as to tell the gc (when the next GC cycle runs) that you no longer need the object.

Upvotes: 2

Related Questions