Reputation: 1284
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();
Upvotes: 9
Views: 8903
Reputation: 6059
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.
Upvotes: 5
Reputation: 3652
Primitive types will be initiated with the default values (0 for int, false for boolean, ...). So it will use the memory size of the type (32 bits for int). See the doc for default values and size
Other objects will be initialized to null
thus using only the reference (usually native pointer size 32 or 64 bits, see this answer) in memory.
Upvotes: 0
Reputation: 2326
If they are instance variables and you don't assign any values
Then for primitives the following default values are assigned:
boolean: false
byte : 0
char : \u0000
short : 0
int : 0
long : 0L
float : 0.0f
double : 0.0d
Objects are initialized to null
Local variables or variables inside methods have to be initialized before they are used or else your code won't compile.
Upvotes: 4