Local variable:
- A local variable is declared inside a method , constructor or block and its scope is limited to that block.
- Only accessible within the method / block where it is declared.
- Not assigned default values - must be initialized before use.
- Stored on the stack.
Global variable or Fields:
- A global variable is declared outside of the method, but inside of a class, making it accessible to all methods of the class.
- Automatically initialized with default values.
- Stored in heap (instance) or method area (static).
- There are two types :
- Instance variable - accessed via objects.
- Static variable - accessed via class.
Static Variable :
- A static variable is a class level variable that is shared by all instance of the class. It is declared using the static keyword.
- Belongs to the class, not to any specific object.
- Only one copy exists in memory, no matter how much objects are created.
- Initialized only once when the class is loaded. Can be accessed directly using the (classname.variablename) or variable name.
Non-Static variable:
- A non static variable ( also known an instance variable) is a variable that belongs to an instance of a class, not the class itself.
- They are declared without the static keyword.
- Each object (instance) of the class gets its own copy of the variable.
- They can be accessed only through object of the class.
Top comments (0)