w1coding.comAll tutorials

Java Static

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Static Keyword

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.

Static Variable

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.

Static Method

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.