Java is an object-oriented programming language that uses variables to store data. In this post, we will discuss the different types of variables in Java: local variables, instance variables, and static or class variables.
Local Variable
Local variables are defined within a method and can only be accessed within that method. They do not have a default value and must be initialized before use. Here is an example of a local variable in Java:
public class LocalVariableExample {
public static void main(String[] args) {
int age; // local variable
age = 25;
System.out.println("My age is: " + age);
}
}
Output:
My age is: 25
Instance Variable
Instance variables, also known as member variables, are defined within a class but outside of any method. They are associated with an object of that class and have a default value of null. Here is an example of an instance variable in Java:
public class InstanceVariableExample {
// instance variable
String name;
public static void main(String[] args) {
InstanceVariableExample obj = new InstanceVariableExample();
System.out.println("My name is: " + obj.name);
}
}
Output:
My name is: null
Static Variable
Static or class variables are defined within a class and outside of any method, but have the ‘static’ keyword before their data type. They are associated with the class, not an object, and have a default value of 0. Here is an example of a static variable in Java:
public class StaticVariableExample {
// static variable
static int count = 0;
public static void main(String[] args) {
StaticVariableExample obj1 = new StaticVariableExample();
obj1.count++;
StaticVariableExample obj2 = new StaticVariableExample();
obj2.count++;
StaticVariableExample obj3 = new StaticVariableExample();
obj3.count++;
System.out.println("Total objects created: " + count);
}
}
Output:
Total objects created: 3
Conclusion
Variables are used to store data in Java. Local variables are defined within a method, instance variables are defined within a class, and static variables are defined within a class and shared among all objects. It’s important to understand the difference between these variable types to write efficient and effective Java code.