简体   繁体   中英

What happens in memory if we just declare a variable without initialization in java?

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();

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 (eg Employee emp = new Employee() ), the JVM assigns a continuous area of heap memory to store it.

While an object is not initialized (eg 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 (eg 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 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 : \

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM