Java Instance Variable Example

This Java example demonstrates the usage of an instance variable in Java with an example.

Java Instance Variable

Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. 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); the empName of one Employee is independent of the empName of another.
Each instance(objects) of a class has its own copy of the instance variable. Unlike a static variable, instance variables have their own separate copy of instance variable.

Java Instance Variable Example

The following demonstrates the meaning of instance variables. The Employee class has fields like idempNameage are instance variables.
package net.javaguides.corejava.variables;

public class InstanceVariableExample {
    public static void main(String[] args) {
        Employee employee = new Employee();

        // Before assigning values to employee object
        System.out.println(employee.empName);
        System.out.println(employee.id);
        System.out.println(employee.age);

        employee.empName = "Ramesh";
        employee.id = 100;
        employee.age = 28;

        // After assigning values to employee object
        System.out.println(employee.empName);
        System.out.println(employee.id);
        System.out.println(employee.age);
    }

}

class Employee {

    // instance variable employee id
    public int id;

    // instance variable employee name
    public String empName;

    // instance variable employee age
    public int age;
}
Output:
null
0
0
Ramesh
100
28

Reference



Comments