Variable
Variable
A variable is a container which holds the value while the program is executed. A variable
is assigned with a data type.Variable is a name of memory location.
local
instance
static.
Local Variable:
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
Instance Variable:
A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
Static:
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
Example:
OutPut:
What is the difference between class variables and instance variables in Java?
Instance variable:
1) Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
2) Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given accessibility),
they should be called using the fully qualified name. ObjectReference.VariableName.
Static variable:
1) Static variables are created when the program starts and destroyed when the program
stops.
2) Static variables can be accessed by calling with the classname ClassName.VariableName.