Java variable types
The Java programming language defines the following kinds of variables:
- Instance Variables
- Static Variables
- Local Variables
Instance Variables (Non-Static Fields)
- Non-Static Variables are called as Instance Variable.
- Instance variables are variables within a class but outside any method.
- Whenever we create an object of class then we can have certain attributes of the class that are unique for each object , that attribute variable is called as “Instance Variable“.
- Individual states of objects is stored in “non-static fields”. (instance variable).
- Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words).
Sample Example
Class Person { String name; int age; String gender; }; Person P1,P2,P3;
In the above example we have created class “Person”. We can have different Attributes of Class Person such as name,age,gender . These attributes are unique for different objects. Such as for object P1’s name can be different from P2’s name. Such variables that are unique for individual object is called Instance Variable.
Class Variables (Static Fields)
- A class variable is any field declared with the static modifier.
- Exactly one copy of static or class variable is created , regardless of how many times the class has been instantiated.
- Suppose we have created 5 objects then all of the objects can share same variable.
Example :
Class Person { String name; int age; String gender; static String city = "Pune"; }; Person P1,P2,P3;
Local Variables
- In order to store Temporary state we use local variables.
- Generally local variables are declared in the methods,constructors,blocks.
- “count” is local variable in following code snippet.
- Destroyed when method gets executed completely.
Example :
int counting(int n1,int n2) { int count; count = n1 + n2; return(count); }