HeadlinesBriefing favicon HeadlinesBriefing.com

Static vs Non‑Static Variables in Java

DEV Community •
×

Java developers often wrestle with the distinction between static and non‑static variables. A non‑static field lives inside a class but outside any method, and every instance of that class receives its own copy. When a new Student object is created, the compiler allocates a fresh marks slot in the heap; one student can hold 80 while another holds 90.

Accessing the field requires an object reference, and each instance can change its value independently. In contrast, a static field belongs to the class itself. Declared with the static keyword, it is created once when the class loads and shared by all objects.

The company_name field in the Employee example illustrates this: every employee instance sees the same company name, and the value resides in the method area rather than the heap. Static members are best reached through the class name, which clarifies that the value is shared. Understanding these memory‑allocation rules helps developers write cleaner, more efficient code and avoid subtle bugs that arise when instance and class data collide.