Table of Contents
All Types of Variables in Java:
In Java we have different names for variable types such as class variable, static variable, member variable, block variable, instance variable & local variable. Sometimes we will get the confusion between these variables.
All Types of Variables in Java:
- Member Variable
- Class Variable
- Static Variable
- Instance Variable
- Block Variable
- Local Variable
Member variables are class variables.
Eg:
[java]
package in.javadomain;
public class MemberVariables {
// instance variable
int instanceMemberVariable;
// class variable/static variable
static int staticMemberVariable;
}
[/java]
Any variable declared for class level is called Member variable.
Member variables are of two types:
1. Static Member Variable/Static Variable/class variable
Class level variable declared with static keyword/static class level variables are called as static variable or class variable.
It will be shared between the different class instances/objects.
It is per class variable. Till the class live in the memory static variables are also alive.
2. Instance Member Variable/Instance Variable
Class level variable declard without static keyword/non-static class level variables are called as instance variable.
It is per instance/per object variable and it lives in the memory till the instance or object exist.
Local variable:
local variabls are created inside the functions/methods.
[java]
package in.javadomain;
public class LocalVariables {
public static void main(String[] args) {
int localVariable;
}
}
[/java]
Block variable:
Block variabls are created/declared/used inside the loops/blocks. Eg: for loop/if/else etc.
[java]
package in.javadomain;
public class BlockVariable {
public static void main(String[] args) {
for(int i=0;i<10;i++){
// i is a blockVariable here.
}
}
}
[/java]
Why static local variables are not allowed in java [or]
Why Can’t I declare a static variable inside the Main method?
Since static variables are shared between the different objects/instances, No use of allowing static variables inside the method, because it allows to keep the same static value in all the objects/instances whichever calls this method. Which looks not fair and waste. So static variables are allowed only in class level not for method levels.