A variable is a container which holds the value while the Java Program is executed. A variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance and static.
There are two types of data types in java: primitive and non-primitive.
TYPES OF VARIABLES
Local Variables
They are declared within a method, constructor or block of code. They are only accessible within the block of code where they are declared.
A local Variable cannot be defined using the “static” keyword.
Instance Variables
They are declared within a class but outside of any method, constructor or block. They are associated with an instance of the class, and each instance of the class has its own copy of the instance variables.
Static Variables
They are declared within a class with a static keyword but outside of any method, constructor or block of code.They are associated with the class rather than with instances of the class.
//Example to understand the types of variable
public class VariableExample {
static int staticVar = 50; //static Variable
int instanceVar = 30; //instance Variable
public static void main(String[] args){
int LocalVar = 40;
System.out.println("static Variable: " + staticVar);
//Creating an instance of the class
VariableExample InstanceObj = new VariableExample();
System.out.println("Instance Variable: " + InstanceObj.instanceVar);
System.out.println("Local Variables: " + LocalVar);
}
}
#Output
static Variable: 50
Instance Variable: 30
Local Variables: 40
staticVar
is a static variable declared at the class level. It’s associated with the class itself rather than instances of the class.instanceVar
is an instance variable declared within the class but outside of any method. Each instance of the class will have its own copy of this variable.localVar
is a local variable declared within themain
method. It is only accessible within themain
method.
Great work mam..thank you