Types of Variables in Java
In Java, variables are containers for storing data values. They can be classified into three types based on their scope and lifetime:
- Local variables: These variables are declared within a method, constructor, or block and have local scope. They are accessible only within the enclosing block and cease to exist once the block is exited.
- Instance variables: These variables are declared within a class but outside any method. They have instance scope and are associated with an instance of the class. They exist as long as the instance of the class exists.
- Static variables: These variables are declared with the static keyword within a class. They have class scope and are associated with the class itself, not with any instance. They are created when the class is loaded and remain in memory until the program terminates.
Here's an example to illustrate the types of variables:
public class VariableExample {
// Instance variable
private int instanceVariable;
// Static variable
private static String staticVariable;
public void exampleMethod() {
// Local variable
int localVar = 10;
// Code using the variables...
}
}
The following diagram illustrates the relationship between the types of variables in Java:
Here's a brief summary of the types of variables:
Type | Scope | Lifetime |
---|---|---|
Local Variable | Within a method, constructor, or block | Created when the block is entered, destroyed when the block is exited |
Instance Variable | Within a class, but outside any method | Created when an instance of the class is created, destroyed when the instance is garbage collected |
Static Variable | Within a class, declared with the static keyword | Created when the class is loaded, destroyed when the program terminates |
Conclusions:
1) For the static and instance variables it is not required to perform initialization explicitly
JVM will provide default values. But for the local variables JVM won’t provide any
default values compulsory we should perform initialization explicitly before using that
variable.
2) For every object a separate copy of instance variable will be created whereas for entire
class a single copy of static variable will be created. For every Thread a separate copy of
local variable will be created.
3) Instance and static variables can be accessed by multiple Threads simultaneously and
hence these are not Thread safe but local variables can be accessed by only one Thread
at a time and hence local variables are Thread safe.