The static
keyword is used for memory management. It can be applied to variables, methods, blocks, and nested classes. A static member belongs to the class, rather than any specific instance of the class.
class Counter { static int count = 0; // Static variable Counter() { count++; // Increment static variable } void display() { System.out.println("Count: " + count); } } public class StaticExample { public static void main(String[] args) { Counter c1 = new Counter(); c1.display(); Counter c2 = new Counter(); c2.display(); } }
In this example, the static variable count
is shared among all instances of the Counter
class. Each time a new object is created, the count is incremented.
class MathUtils { static int add(int a, int b) { // Static method return a + b; } } public class StaticExample { public static void main(String[] args) { int result = MathUtils.add(5, 3); // Calling static method without object System.out.println("Sum: " + result); } }
Static methods can be called without creating an object of the class. In this example, the add()
method is static and called directly from the class.