Java Instance Variable Example

A variable is a container which holds the value while the Java program is executed.
Instance variable in Java is used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any method declaration are Object specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances.

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

Rules for Instance variable in Java

  • Instance variables can use any of the four Access Modifiers - Public, Private, Protected & Default
  • They can be marked final
  • They can be marked transient
  • They cannot be marked abstract
  • They cannot be marked synchronized
  • They cannot be marked strictfp
  • They cannot be marked native
  • They cannot be marked static

Related Examples

Reference

Comments