what is instance variable in programming? what is its scope and memory allocation?

 Instance Variable :

Declaration: A instance variable is declared inside the class but outside the methods ,blocks or constructors.

for example 

class Math{

int a=10;  // here a is a instance variable.

void add(){

int c=30,d ;

d=a+ b+ c;

System.out.println(d);

}}

Scope: Instance Variable can be used inside all methods ,blocks and constructors within a class( not inside the static method directly).

When variable gets memory allocated : Instance Variable gets memory allocated when the object is created, when objects get destroyed variable releases memory.

Stored memory : Instance variables are stored in heap memory(part of memory allocated to JVM).

Default value : Instance Variables have default values like Integer :0 , Boolean :false ,  object :  null.

Access specifier : Access specifiers i.e, public protected, private can be used with Instance Variable.

How to access : Instance Variables can be called directly or by using object name.   

Post a Comment

have you any doubt then ask.

Previous Post Next Post