what is static variable in programming? how it is declared and scope of static variable?

 Static Variable : A variable which is declared using  static keyword is known as static variable. it cannot be local. It is accessible for all instance of classes. memory allocation for static variable happens only once when the class is loaded in the memory.

Class Math{

int a=10;

Static int b=4; // b is Static variable

void add(){

int c=30 ,d ;

d=a+ b+ c;

System.out.println (d);

} }

Declaration : It is declared by using static keyword inside the class but outside the body of the methods, constructor or blocks.

Scope : It can be used inside all methods , constructor or blocks.

When variable get memory allocated : When we run program and class file is loaded in JVM , static variable gets allocated. when class file gets unloaded from JVM static variable gets destroyed.

Stored memory : Static variables are stored in static memory or non-heap memory.

Default Values :Static variables have default values like Integer: 0, Boolean : false , Object :null .

Access Specifier : Access Specifier that is public , protected ,private can be used with static variables.

How to access : Static variables can be called by three ways.

                                 1. By Called directly.

                                   2. By using Class name .

                                3. By using Object reference name . 


3 Comments

have you any doubt then ask.

Previous Post Next Post