Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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();
like image 484
Naveen Avatar asked Apr 30 '15 12:04

Naveen


People also ask

What happens if you don't initialize a variable in Java?

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.

What will happen if you use the variable without initializing it?

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.

Can we declare a variable without initializing in Java?

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.


1 Answers

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.

like image 133
user1438038 Avatar answered Oct 18 '22 19:10

user1438038