DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

Local, Global, Static and Non-Static Variables

Local variable:

  1. A local variable is declared inside a method , constructor or block and its scope is limited to that block.
  2. Only accessible within the method / block where it is declared.
  3. Not assigned default values - must be initialized before use.
  4. Stored on the stack.

Global variable or Fields:

  1. A global variable is declared outside of the method, but inside of a class, making it accessible to all methods of the class.
  2. Automatically initialized with default values.
  3. Stored in heap (instance) or method area (static).
  4. There are two types :
  5. Instance variable - accessed via objects.
  6. Static variable - accessed via class.

Static Variable :

  1. A static variable is a class level variable that is shared by all instance of the class. It is declared using the static keyword.
  2. Belongs to the class, not to any specific object.
  3. Only one copy exists in memory, no matter how much objects are created.
  4. Initialized only once when the class is loaded. Can be accessed directly using the (classname.variablename) or variable name.

Non-Static variable:

  1. A non static variable ( also known an instance variable) is a variable that belongs to an instance of a class, not the class itself.
  2. They are declared without the static keyword.
  3. Each object (instance) of the class gets its own copy of the variable.
  4. They can be accessed only through object of the class.

Top comments (0)