Variable Types in Java
![](https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*dt39AffRDnSCySSE_jysHg.png)
When writing programs, variables are used to store data that can be accessed and manipulated throughout the execution of the code. Three main types of variables serve different purposes. Those variable types are member variables, class variables, and local variables. Understanding the differences between these variable types is important for effectively utilizing them in your programs.
If you don’t have a medium membership, you can use this link to reach the article without a paywall.
Member Variables(Instance Variables)
Member variables, also known as instance variables, are attributes of a class. A class declares member variables within the class but outside of any method. They represent data that is specific to individual objects instantiated from the class. In other words, these variables define the characteristics or properties of objects created from the class.
Unlike local variables (which we’ll discuss shortly), member variables persist as long as the object to which they belong exists. They encapsulate the state of an object, representing its attributes.
public class Person {
// Member variable
String name;
// Constructor
public Person(String name) {
this.name = name;
}
}
Here, name
is a member variable. The Person class declares name
as a member variable outside of any method. Each Person object will have its own name field. The constructor sets a name field for each Person object.
Some key points about member variables:
- The class defines member variables at the class level. This makes them available to all methods, constructors and blocks in the class.
- Also known as instance variables as they represent data associated with class instances.
- Member variables remain valid from when an object is instantiated until the object goes out of scope.
- There will be a separate copy of the member variable for each object instance.
- Accessible via the dot operator (obj.variable) from outside the class.
For example:
Person p1 = new Person("John");
Person p2 = new Person("Sarah");
p1.name; // Evaluates to "John"
p2.name; // Evaluates to "Sarah"
Here p1 and p2 are two distinct Person objects, each with its own name member variable set via the constructor.
Local Variables
A method, constructor, or block of code declares local variables that have limited scope. They exist only within the block of code where they are declared and are typically used for temporary storage. The execution of a block of code causes any local variables declared within it to go out of scope, making them inaccessible.
For example:
public class Calc {
public int sum(int num1, int num2) {
// Local variable
int result;
result = num1 + num2;
return result;
}
}
Here, ‘result’ is a local variable declared within the sum() method to temporarily store the sum of the parameters num1 and num2.
Some key points about local variables:
- Declared inside methods, constructors, or blocks.
- Visible only within the declared scope, not across methods or classes.
- Exist only during execution of the scope in which they are declared.
- There is a separate copy of a local variable for each invocation of the method.
- Not accessible from outside their declared scope.
For example:
public class Main {
public static void main(String[] args) {
int num = 5; // Local variable
}
public void print() {
System.out.println(num); // Error, num not visible here
}
}
Here num is a local variable declared in the main() method. The print() method cannot access it since the main() method limits its scope.
Class Variables(Static Variables)
Class variables, also known as static variables
, are variables declared with the static
keyword. They are inside a class but outside any method, constructor, or block. They represent data associated with the class rather than individual objects.
A class shares class variables among all its instances. So, Unlike member variables, they are declared with the static
keyword. Hence, their values are the same for every object of the class. A class often uses class variables to represent constants or properties common to all its instances.
For example:
public class Person {
// Class variable
static int count = 0;
// Constructor
public Person() {
count++;
}
}
Here, ‘count’ is a class variable that keeps track of the total number of Person objects instantiated.
Some key points about class variables:
- Declared using the ‘static’ modifier at the class level.
- There is only one copy of the static variable shared across all objects of that class.
- Accessed via the class name rather than a particular object (Person.count).
- Also known as static fields as they represent data associated with the entire class.
For example:
Person p1 = new Person();
Person p2 = new Person();
p1.count; // 2
p2.count; // 2
Person.count; // 2
Here p1.count and p2.count refer to the same static variable Person.count which increments with each object created.
Differentiating Use Cases
Understanding when to use member variables, class variables, and local variables is crucial for designing robust and efficient Java programs.
- Member variables encapsulate the state of objects and are unique to each instance. They represent the characteristics or properties of an object.
- A class shares class variables among all its instances to represent constants or shared properties. They provide a centralized piece of information for all objects of a class.
- Local variables are temporary and have limited scope within a method or block. They are handy for performing specific calculations or storing temporary values.
In conclusion, member variables, class variables, and local variables play distinct roles in Java programming. Understanding the differences and use cases of these variable types will help you organize data appropriately in your programs.
Objects should use member variables for object-specific data. A class should use class variables for values shared across the class. Local variables should be used for temporary values in short scopes.
👏 Thank You for Reading!
👨💼 I appreciate your time and hope you found this story insightful. If you enjoyed it, don’t forget to show your appreciation by clapping 👏 for the hard work!
📰 Keep the Knowledge Flowing by Sharing the Article!
✍ Feel free to share your feedback or opinions about the story. Your input helps me improve and create more valuable content for you.
✌ Stay Connected! 🚀 For more engaging articles, make sure to follow me on social media:
🔍 Explore More! 📖 Dive into a treasure trove of knowledge at Codimis. There’s always more to learn, and we’re here to help you on your journey of discovery.