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); } }
3 3
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); } }
1 2