[java] When to create variables (memory management)

You create a variable to store a value that you can refer to that variable in the future. I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

If I were to have a variable that I won't be referring to agaon, would removing the reference/value vars I'm using (and just using the numbers when needed) save memory? For example:

int number = 5; public void method() {     System.out.println(number); } 

Would that take more space than just plugging '5' into the println method?

I have a few integers that I don't refer to in my code ever again (game loop), but I've seen others use reference vars on things that really didn't need them. Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

The answer is


I've heard that you must set a variable to 'null' once you're done using it so the garbage collector can get to it (if it's a field var).

This is very rarely a good idea. You only need to do this if the variable is a reference to an object which is going to live much longer than the object it refers to.

Say you have an instance of Class A and it has a reference to an instance of Class B. Class B is very large and you don't need it for very long (a pretty rare situation) You might null out the reference to class B to allow it to be collected.

A better way to handle objects which don't live very long is to hold them in local variables. These are naturally cleaned up when they drop out of scope.

If I were to have a variable that I won't be referring to agaon, would removing the reference vars I'm using (and just using the numbers when needed) save memory?

You don't free the memory for a primitive until the object which contains it is cleaned up by the GC.

Would that take more space than just plugging '5' into the println method?

The JIT is smart enough to turn fields which don't change into constants.

Been looking into memory management, so please let me know, along with any other advice you have to offer about managing memory

Use a memory profiler instead of chasing down 4 bytes of memory. Something like 4 million bytes might be worth chasing if you have a smart phone. If you have a PC, I wouldn't both with 4 million bytes.


In your example number is a primitive, so will be stored as a value.

If you want to use a reference then you should use one of the wrapper types (e.g. Integer)


So notice variables are on the stack, the values they refer to are on the heap. So having variables is not too bad but yes they do create references to other entities. However in the simple case you describe it's not really any consequence. If it is never read again and within a contained scope, the compiler will probably strip it out before runtime. Even if it didn't the garbage collector will be able to safely remove it after the stack squashes. If you are running into issues where you have too many stack variables, it's usually because you have really deep stacks. The amount of stack space needed per thread is a better place to adjust than to make your code unreadable. The setting to null is also no longer needed


It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.


Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.

Nonprimitive (ints, chars, doubles, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.

On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.

In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.

And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.

Java's actually very nicely made so that you shouldn't have to worry about nulling variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.

*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with variables tag:

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes? Passing Variable through JavaScript from one html page to another page Printing variables in Python 3.4 Python Function to test ping Declaring variable workbook / Worksheet vba Removing spaces from a variable input using PowerShell 4.0 How to modify a global variable within a function in bash? Bash: Echoing a echo command with a variable in bash set value of input field by php variable's value How to delete an instantiated object Python? Increment variable value by 1 ( shell programming) How to pass parameters or arguments into a gradle task How would I access variables from one class to another? What is a None value? How to remove a newline from a string in Bash Set environment variables from file of key/value pairs Convert dictionary to bytes and back again python? When should an Excel VBA variable be killed or set to Nothing? Add php variable inside echo statement as href link address? Getting the name of a variable as a string SQL variable to hold list of integers How can I do division with variables in a Linux shell? Append integer to beginning of list in Python ReferenceError: variable is not defined Length of string in bash Importing variables from another file? How can I print variable and string on same line in Python? jQuery: using a variable as a selector Create timestamp variable in bash script PHP: get the value of TEXTBOX then pass it to a VARIABLE How to base64 encode image in linux bash / shell Remove an element from a Bash array python: how to identify if a variable is an array or a scalar jQuery return ajax result into outside variable Pass variables between two PHP pages without using a form or the URL of page printf a variable in C Dynamic variable names in Bash How to check if a variable is an integer or a string? How can I test that a variable is more than eight characters in PowerShell? Assign command output to variable in batch file How to swap two variables in JavaScript

Questions with memory-management tag:

When to create variables (memory management) How to check if pytorch is using the GPU? How to delete multiple pandas (python) dataframes from memory to save RAM? Is there a way to delete created variables, functions, etc from the memory of the interpreter? C++ error : terminate called after throwing an instance of 'std::bad_alloc' How to delete object? Android Studio - How to increase Allocated Heap Size Implementing IDisposable correctly Calculating Page Table Size Pointer-to-pointer dynamic two-dimensional array Releasing memory in Python What does 'corrupted double-linked list' mean malloc for struct and pointer in C What are the -Xms and -Xmx parameters when starting JVM? Where in memory are my variables stored in C? How to check heap usage of a running JVM from the command line? What are the differences between virtual memory and physical memory? What's the difference between .so, .la and .a library files? Memory Allocation "Error: cannot allocate vector of size 75.1 Mb" What does this GCC error "... relocation truncated to fit..." mean? How to deal with bad_alloc in C++? Calculate size of Object in Java How do I free memory in C? Difference between static memory allocation and dynamic memory allocation How to dynamically allocate memory space for a string and get that string from user? Why should C++ programmers minimize use of 'new'? Can a local variable's memory be accessed outside its scope? ios app maximum memory budget How to list processes attached to a shared memory segment in linux? R memory management / cannot allocate vector of size n Mb How to get system time in Java without creating a new Date What is the correct Performance Counter to get CPU and Memory Usage of a Process? Objective C - Assign, Copy, Retain Max value of Xmx and Xms in Eclipse? Is it safe to delete a NULL pointer? Allowed memory size of X bytes exhausted Attempted to read or write protected memory. This is often an indication that other memory is corrupt In Linux, how to tell how much memory processes are using? Difference between logical addresses, and physical addresses? Deleting an object in C++ How to get current memory usage in android? Is "delete this" allowed in C++? What is the default maximum heap size for Sun's JVM from Java SE 6? How can I give eclipse more memory than 512M? delete vs delete[] operators in C++ Read large files in Java How do I discover memory usage of my application in Android? @property retain, assign, copy, nonatomic in Objective-C How to initialise memory with new operator in C++? What is private bytes, virtual bytes, working set?

Questions with reference tag:

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference " Meaning of "referencing" and "dereferencing" in C Does JavaScript pass by reference? Reference member variables as class members What is the difference between "::" "." and "->" in c++ Strict Standards: Only variables should be assigned by reference PHP 5.4 How do I make a relative reference to another workbook in Excel? Reason to Pass a Pointer by Reference in C++? How to cast/convert pointer to reference in C++ C++ pass an array by reference How to add a reference programmatically How to return a class object by reference in C++? Android: failed to convert @drawable/picture into a drawable What's the difference between primitive and reference types? python list by value not by reference Pass by pointer & Pass by reference How do I copy the contents of one ArrayList into another? error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’ Undefined reference to main - collect2: ld returned 1 exit status Python List & for-each access (Find/Replace in built-in list) What is a constant reference? (not a reference to a constant) When to use references vs. pointers How to disable Excel's automatic cell reference change after copy/paste? JavaScript by reference vs. by value Creating a copy of an object in C# Reference an Element in a List of Tuples What does the "undefined reference to varName" in C mean? Meaning of *& and **& in C++ MongoDB relationships: embed or reference? What exactly is an instance in Java? The type or namespace name could not be found Could not load file or assembly '***.dll' or one of its dependencies Is null reference possible? Referenced Project gets "lost" at Compile Time Namespace not recognized (even though it is there) Referencing a string in a string array resource with xml Pick images of root folder from sub-folder A reference to the dll could not be added Getting "type or namespace name could not be found" but everything seems ok? In laymans terms, what does 'static' mean in Java? Difference between const reference and normal parameter

Questions with garbage-collection tag:

When to create variables (memory management) Difference between Xms and Xmx and XX:MaxPermSize Java GC (Allocation Failure) How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors? Implementing IDisposable correctly How to check heap usage of a running JVM from the command line? how to destroy an object in java? How to force deletion of a python object? How can I read a large text file line by line using Java? GC overhead limit exceeded How to exit an application properly What is the garbage collector in Java? Garbage collector in Android Do you need to dispose of objects and set them to null? When is the finalize() method called in Java? Why is it bad practice to call System.gc()? Where Is Machine.Config? Java heap terminology: young, old and permanent generations? How to free memory in Java? How to force garbage collection in Java? Error java.lang.OutOfMemoryError: GC overhead limit exceeded How to redirect verbose garbage collection output to a file? How to monitor Java memory usage? Java Garbage Collection Log messages What is JavaScript garbage collection? Deleting Objects in JavaScript Proper use of the IDisposable interface When is it acceptable to call GC.Collect? Stack, Static, and Heap in C++ Best Practice for Forcing Garbage Collection in C# Is there a destructor for Java? When should I use GC.SuppressFinalize()? Why doesn't C++ have a garbage collector? When does System.gc() do something?