2.static variable:-
- If the value of a variable is not varied from object to object then it is not recommended to declare variable as instance variable.We have to declare that variable static variable.
- In the case of static variable a single copy will be created and shared by every object of the class.
- Static variable should be declare within the class directly but outside of any method/block/constructor.
- Static variable will be stored in the method area.
- Static variable is created at the time of class loading & destroyed at the time of class unloading.So the scope of the static variable is exactly same as the scope of .class file.
The following activities happen whenever we run the .class file for example
java Test
- start JVM
- create & start the main thread
- locate the .class file
- load the .class file
- execute .class file
- unload .class file
- terminate the main thread
- shutdown the JVM
- We can access the static variable either by object reference or by class name,but it is not recommended to use class name.
- Within the same class it is not require to use class name & we can access directly.
- We can access the static from both instance & static area.
example:
|
javachetan.blogspot.com | | | | | | | |
3.local variable:-
- Sometime we need a variable for temporary use.We can declare variable inside a method/block/constuctor such type of variable are called local variable.
- Local variable will be stored in the stack memory.
- Local variable will be created while executing the block in which we declared it.once the execution completed, automatically local variable will be destroyed.Hence the scope of local variable the block in which it declared.
example :-
|
javabychetan.blogspot.com |
- For local variable JVM won't provide default values.If are not using then it is not required to perform initilization.
- If we are using compulsory we should perform initilization explicitly before using that variable.Other wise we will get compile time errors.
example:-