Java - When a global variable is declared and initialized with a value, the what happens while object creation?

Viewed 436

When a global variable is declared and initialized with a value, then while creating object of the class, is the global variable again gets initialized and gets a new memory?

class A{

int a = 10;

}

This will gets stored in the memory address a with value 10. But when I create object of the class A, then is the a gets initialized again?

class A{

int a = 10;

public static void main(String args[]){

A a = new A();

}
3 Answers

When a global variable is declared and initialized with a value...

What you have shown is not a global variable. Truly global variables do not exist in Java. a is an instance field of A.

This will gets stored in the memory address a with value 10.

a is not a memory address, it is just the name of the field. You rarely need to deal with low-level stuff such as memory addresses in Java.

But when I create object of the class A, then is the a gets initialized again?

Before you create an instance, no memory is allocated for the a field, except maybe for storing the compiled class file itself. It is once you create an instance of A that there is a place in memory storing the value 10 that corresponds to the a field of that instance.

Note that if you create a second instance of A, another piece of memory will be allocated to hold the a of that instance.

what you said is not quite how memory allocation works.

class A{

int a = 10;

}

in the above example you created a class. the members in the class are only created and assigned their values after their objects are created unless the the members are declared as static. hence the variable 'a' is assigned the value 10 after the construction of the object 'a' of class A in the second example you posted. If you still don't understand, then run this code:

class A{
int a = 10;
public static void main(String args[]){
A a = new A();
A b = new A();
b.a += 10;
System.out.println(a.a);
System.out.println(b.a);
}
}

if the variable a was assigned before creation of object, then when object b modifies it, the variable printed would change. But if you run this the out put will be:

10
20

which means that the variables only got assigned after object creation. I hope this clears your doubt. Also another tip for you, Static variables cannot be modified.

There is no global variables in Java. There are class and object variables. Class variables are defined by the static keyword.

In your code, the a variable is an object variable, it is created (and initialized) every time a new object of the class is created, in this case, with the call new A().

If you created another object of the class A, another object variable awould be created (and initialized) for it, different that the first one.

Related