What happens in memory if we just create a reference variable or declare a variable for primitive data types or reference data types without initializing with any value as below?
int x;
Employee emp;
So what exactly happens in memory in both the cases?
Is any memory allocated at this stage or does it point to any random location or points to null or points to garbage values?
As in the 2nd case, only space will created in memory if we create a object using the constructor with new operator or using any other ways like.
Employee emp = new Employee();
Declaring final variable without initialization If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.
Solution. If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value. Whenever we declare a variable, a location is allocated to that variable.
Declaring final variable without initialization If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
The Java Virtual Machine (JVM) allocates heap memory from the operating system and manages its own heap for Java applications afterwards. When an application creates a new object (e.g. Employee emp = new Employee()
), the JVM assigns a continuous area of heap memory to store it.
While an object is not initialized (e.g. Employee emp = null
), there is no need to allocate any memory. Primitive types (in the global scope), however, are initialized with a default value, even if you do not set it explicitly (e.g. int x
is in fact int x = 0
). So in this case, memory will be allocated, too.
As long as a reference to the object is kept anywhere within the application, the object remains in memory. Objects that are no longer referenced will be disposed by the garbage collector (GC) and will be cleared out of the heap to reclaim their space.
The String
class also allocates heap memory, uses a little tweak though: String interning is used, as soon as you allocate multiple instances of String
with the same text. So, in fact you will only have one instance in memory, but multiple variables that reference it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With