Difference Between Local, Instance, and Static Variables in JavaVariables are crucial parts that store data in the realm of Java programming. Static variables and local instance variables are the two most prevalent forms of variables. Although they both have the function of storing data, they differ in terms of features and applications. In this section, we will discuss the differences between local, instance, and static variable. Local Instance VariablesLocal instance variables are linked to a specific class instance and are also called instance variables. They are declared inside classes, but outside of any constructors, methods, and blocks. These variables are created and linked to class objects that are instantiated. Car.java Output: Brand: Toyota Year: 2022 Brand: Honda Year: 2017 Explanation Year and brand are local instance variables in this case. These variables are specific to each instance of the Car class (car1 and car2) and may have distinct values. Instance VariablesInstance variables are variables defined inside a class that are not included in any constructor, method, or block. They are sometimes referred to as member variables or object variables. These variables are connected to the class's instances or objects. Person.java Output: Person 1: Name: Ram Age: 25 Person 2: Name: Ravi Age: 30 Explanation The instance variables' name and age are set to distinct values when two Person objects, p1 and p2, are created in the main() method. Every object has its displayInfo() method called on it, which outputs the name and age values correspondingly. The names and ages of both people are consequently shown to you in the output. Static VariablesIn contrast, static variables are linked to the class itself and not to a particular instance of the class. They exist apart from all other objects and are specified with the static keyword. A static variable is shared by all instances of the class and exists only in one copy for the whole class. Value.java Output: Count variable Value: 2 Local Vs. Instance Vs. Static Variables
ConclusionIn conclusion, static variables are shared by all instances of a class, whereas local instance variables are unique to each instance. Which option we choose will rely on the particular needs of Java program. For your Java programmes to use variables effectively and efficiently, we must be aware of their differences. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India