Java Static vs Instance

1. An instance variable is one per Object, every object has its own copy of instance variable.

Eg:

public class Test{

   int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will have its own copy of x.

2. A static variable is one per Class, every object of that class shares the same Static variable.

Eg:

public class Test{

   public static int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

Both t1 and t2 will have the exactly one x to share between them.

3. A static variable is initialized when the JVM loads the class.

4. A static method cannot access Non-static variable or method.

5. Static methods along with Static variables can mimic a Singleton Pattern, but IT’S NOT THE RIGHT WAY, as in when there are lots of classes, then we can’t be sure about the class loading order of JVM, and this may create a problem.

Leave a Comment

tech