Variables are used to hold some value within the Java program. You can define the variable with the data type and can assign the value of that particular data type.
A variable can be the name given to the memory location. It can be of three types - local, instance, and static. Two data types - primitive and non-primitive can be used for the variables within Java.
What are Variables?
Variables are those whose values can be changed. The name specifies the memory allocated that can contain a value.
Types of Variables
Variables can be classified based on their scope. There are three types of variables.
1. Local variable
A variable whose scope exists within the method is called the local variable. Other methods within the class cannot access this variable. You cannot declare a local variable with the static keyword.
2. Instance variable
The variable which is declared within a class but outside the method body is called the instance variable. You cannot declare this variable as static. The value of this variable depends on the instance and cannot be shared among different instances. It means you cannot use this variable within another class.
3. Static Variable
Once a variable is declared as static, you cannot declare it as local. You can use the static variable among all instances of the class. The memory will be allocated for the static variable only once when the class gets loaded in memory.
int var1=50;//instance variable
static int var2=100;//static variable
int var3=90;//local variable
} }//end of class