DEV Community

Cover image for #4 Known is a drop! Class Variables -Static Variable and Instance variable and Local variables
Deepikandas
Deepikandas

Posted on • Edited on

#4 Known is a drop! Class Variables -Static Variable and Instance variable and Local variables

There are three types of variables:
1.Static Variable (gets default values)-- Also called Fields
2.Instance Variable(gets default values)Also called Fields
3.Local variable(No default values)

STATIC VARIABLE:

  • Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

  • Fields that have the static modifier in their declaration are called static fields or class variables.

  • you cannot declare a static variable inside a method in Java.

  • Every instance of the class shares a class variable, which is in one fixed location in memory.
    Static (class-level) variables can be manipulated directly using the class name, without instantiating the class.

  • Static variables can be accessed with class name across other class.Within the same class,within static method or non static method,no need of class name to access static variable.

  • Static variables can be used both in static methods and non static methods without using object reference

  • Value assigned to static variable can be changed anytime, at any part of the program.


Instance Variables:

  • Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword.

  • Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words);

  • Non static variables/instance variables can be used in non static method directly(no need of object reference),whereas while using instance variables in static methods,object ref is needed.

Local Variable:
A method will often store its temporary state in local variables. eg: int id=16;
There is no special keyword designating a variable as local;
Local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

Top comments (0)