Local variables — declared and exist only within the body of a method or block, not initialized automatically. Using an uninitialized local variable results in a compilation error.
Instance variables (non-static fields) — belong to each object separately, initialized when an instance of the object is created.
Static variables (static fields) — common to all instances of the class, exist as a single instance for the entire class. Their modification in one object is visible in all other objects of that class.
public class Example { private int instanceVar; // instance variable private static int staticVar; // static variable public void foo() { int localVar = 0; // local variable } }
Can static variables be private and how are they seen between different instances of the class?
Answer: Yes, static variables can be private. Their modification is reflected for all instances of the class, as they belong to the class, not the object.
public class MyClass { private static int counter = 0; public MyClass() { counter++; } public static int getCounter() { return counter; } }
Creating multiple instances of MyClass will increment the same counter.
Story
In an enterprise application, a developer mistakenly placed user state in a static field. This resulted in users "seeing" each other's data in a multi-user environment.
Story
While writing a multithreaded application, an instance variable was used inside a static method without proper synchronization. This led to data races and unexpected results.
Story
A developer chose to use a local variable instead of a class field to store an intermediate result. The variable was destroyed after exiting the method, and the program always returned null, which was not discovered immediately during testing.