The static keyword in Java is used to define class-level members. Static members belong to the class itself rather than to individual objects.
// Example demonstrating static variable and method
class Counter {
static int count = 0;
static void increment() {
count++;
}
public static void main(String[] args) {
Counter.increment();
Counter.increment();
System.out.println(count);
}
}
2
The static variable count is shared across method calls. Each call to increment() updates the same variable.
Click the buttons below to see how memory works differently for Static vs Instance variables.
Changes everywhere!