Java – static and instance variables

Static variables are created once for a class and shared by all instances. Static variable is created the moment class is loaded.

static variable example

public class Main {
  public static int val = 0;
  public Main() {}
  public static void main(String[] args) {
    Main obj1 = new Main();
    obj1.val += 1;
    Main obj2 = new Main();
    obj2.val += 2; // val becomes 3 as both objects refer to same variable
    System.out.println(obj1.val);
    System.out.println(obj2.val);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   20456
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

instance variable example

public class Main {
  public int val;
  public Main() {
    val = 0;
  }
  public static void main(String[] args) {
    Main obj1 = new Main();
    obj1.val += 1;
    Main obj2 = new Main();
    obj2.val += 2; // both objects refer to different variables
    System.out.println(obj1.val);
    System.out.println(obj2.val);
  }
}
OpenJDK 64-Bit Server VM warning: Insufficient space for shared memory file:
   20468
Try using the -Djava.io.tmpdir= option to select an alternate temp location.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments