Classification of Java Variables and Member Variables
Variables in Java are categorized based on their scope, lifetime, and association with classes or instances.
- Local Variables: Declared within methods, constructors, or code blocks. They are destroyed when the enclosing execution context exits and must be explicitly initialized before use.
- Instance Variables: Declared in a class but outside methods/constructors. Each class instance maintains its own copy. If uninitialized, they receive default values (0 for numerics,
falsefor booleans,nullto references). - Static Variables (Class Variables): Declared with the
statickeyword. Shared across all class instances, initialized once during class loading. Accessed viaClassName.variableName. - Constants: Member variables marked
static final. Immutable, single copy per class. - Parameter Variables: Defined in method/constructor signatures to accept input values. Scoped to the method body. Example:
// beverageType is a parameter variable
public void drink(String beverageType) {
System.out.println("Today I drank " + beverageType);
}
In summary, variables fall into three groups: local, member (instance/static/constant), and parameter variables.
Member Variables and Field-Property Distinction
Member Variables: Scope spans the entire class (similar to C globals), declared outside methods. Encludes instance variables, static variables, and constants.
Fields vs. Properties:
- Fields: Synonymous with member variables (instance/static/connstants) declared in a class.
- Properties: Defined by accessor methods (
getXxx()/setXxx()), independent of direct field storage. A property exists if at least one accessor is present.
Example with property accessors:
public class Person {
private int age; // Field
// Readable age property
public int getAge() {
return age;
}
// Writable age property
public void setAge(int newAge) {
age = newAge;
}
}
A class with both accessors has a read-write property; only a getter implies read-only, only a setter implies write-only. Properties may lack backing fields (computed properties):
public class Rectangle {
private double width; // Backing field
private double height; // Backing field
// Computed area property (no dedicated field)
public double getArea() {
return width * height;
}
}
Default Values
Local variables require explicit initialization. Member variables use implicit defaults:
| Variable Type | Default Value |
|---|---|
| int, byte, short, long | 0 |
| float, double | 0.0 |
| char | '\u0000' |
| Reference types | null |