In java we have 3 types of variables based on the area of declaration.
Local variables.
Instance Variables.
Static Variables.
Local Variable
Variables which are declared inside a method , constructor or block called local variable.
Local variable will be created when the method or code block is executed by JVM and
destroyed after the method execution.
No Access modifiers are allowed with a local variable.
These variables are created in stack memory.
There is no default value for local variables , we must initialize before the first usage of the
variable.
Instance Variables
Variables which are declared inside a class but not inside any method , constructor or blocks.
This variables are created when object is created to that class and destroyed when the object
is cleared from memory.
We should declare Instance variables when we need to refer the same variable in multiple
methods or blocks.
We can use all the Access modifiers with instance variables, generally we use private in IT
industry.
Instance variables have default values provided by JVM, for numbers the default value is zero ,
for Boolean variables it is false, for objects it is null.
These variables value can be set in multiple ways.
1)At the time of declaration we can set.
2)Through Constructor.
3)Through getter and setter methods.
4)Through Object reference.
Static Variables
Static variables are also called as Class Variables.
These variables are also declared inside a class but not inside any method or block.
Static key word is used along with the variable declaration.
The major difference with static and non static variables is the Memory allocation.
Access modifiers usage is similar to instance variables.
Default values are also same as instance variables,
For numbers zero ,Boolean – false, objects – null.
Static variables are accessed with the class name.
Syntax: [Link]
In our day to day programming , we use static when the variable should be constant in entire
application.
example : public static final int favouriteNumber=2;
msclns
Variable which hold primitive values are called primitive variables remaining are called
reference variables.
We know 8 primitive data types in java , but what are these reference variables?
ex: int id=200; (id is primitive variable);
Employee e;(Here e is reference variable)
• We can not use instance variable in static area.
Static Methods vs Non Static
Like variables we have two types of methods also
1)Static Method
2)Non Static method.