Static vs Non Static in Java: Key Differences and Usage
static means a member belongs to the class itself, shared by all objects, while non-static members belong to individual objects. Static members can be accessed without creating an object, but non-static members require an instance of the class.Quick Comparison
Here is a quick table comparing static and non-static members in Java.
| Factor | Static | Non-Static |
|---|---|---|
| Belongs to | Class itself | Instance (object) |
| Access | Without creating object | Requires object |
| Memory | Single copy shared | Separate copy per object |
| Can access | Only static members directly | Both static and non-static members |
| Use case | Utility methods, constants | Object-specific data and behavior |
| Example | static int count; | int age; |
Key Differences
Static members belong to the class itself, so they are shared by all instances. This means if you change a static variable, the change is seen by all objects of that class. Static methods can be called without creating an object, making them useful for utility or helper functions.
Non-static members belong to individual objects. Each object has its own copy of non-static variables, so changes affect only that object. Non-static methods can access both static and non-static members, but static methods cannot directly access non-static members because they do not belong to any object.
In summary, use static when you want to share data or behavior across all objects, and use non-static when data or behavior is specific to each object.
Code Comparison
This example shows a static variable and method used to count how many objects are created.
public class Counter { static int count = 0; // static variable shared by all public Counter() { count++; // increment count when object is created } static void showCount() { // static method System.out.println("Count: " + count); } public static void main(String[] args) { new Counter(); new Counter(); Counter.showCount(); } }
Non-Static Equivalent
This example uses a non-static variable and method to track count per object.
public class Counter { int count = 0; // non-static variable unique to each object public Counter() { count++; // increments only this object's count } void showCount() { // non-static method System.out.println("Count: " + count); } public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); c1.showCount(); c2.showCount(); } }
When to Use Which
Choose static when you need a single shared value or method that does not depend on object state, like utility functions or constants. Use non-static when each object should have its own data and behavior, such as properties that differ per instance. Static is great for shared resources, while non-static is essential for object-specific information.