Difference Between Local, Static And Instance Variables

By Venkatesh Kolipaka
12-11-2018
3676

Difference Between Local, Static and Instance Variables

Variable:  A variable is named memory location, which holds a particular type of data. In java variable must be declared before using it.

In java we have three types of variables are there,

they are:

Ø Local

Ø Static (Class Level)

Ø Instance (Object Level)

Local Variable:

 The variable which is declared in methods, constructors, or blocks.

The memory allocated once the controller enters into the methods, constructors, or blocks and the variables area destroyed once the controller exit the methods, constructors, or blocks.

The scope the local variable is within the methods, constructors, or blocks in which it is declared, so we cannot access the local variable outside the methods, constructors, or blocks in which it is declared.

The JVM will not assign any default value to the local variables, so we must assign value to it before we are using it. If we try to access local variable before initialised then will get compiler error saying The local variable local may not have been initialized”.

Static (Class Level):

 The variable which is declared with the key word static the variable is said to be a static variable. The static variables are initialised when the class is loaded. The memory will have allocated only once. The value of the static variable is shared among the various objects of that class. Default value assaigned by the JVM is 0 for int, null for string, 0.0 for double and float etc. In the example given the variable “a” which is type of int, in the console we can see the output as 0 which is the default value.



Instance (Object Level):

If a variable declared not with the static key word and not declared in block or method then the variable is called as Instance variable.

We can access the instance variable throughout the class and the value may get vary depends upon the object created on it. The default value for instance variable is zero(0) for int, 0.0 for double, 0.0 for float and null for strings etc.

 


 



Related Tutorials