Monday, February 16, 2026

Static

Static Declarations in Java

Static Declarations in Java

A top‑level class, interface, or enum cannot be declared static. This restriction exists because static is meaningful only in the context of an owning type. For example, a class Request may contain a static nested class Data, meaning Request owns Data statically. But Request itself cannot be static because it is not owned by any other type.

Similarly, local members—that is, members declared inside a method—cannot be static. Therefore, the following code will fail to compile:

class TestClass {

    public static void main(String[] args){

        static int x;      // cannot be static
        static class Y {   // cannot be static

        }

    }

}
    

Does this mean that the variable x and the class Y are instance members? No. They are not members of the class at all. They are local to the method, and therefore the concepts of static vs. instance do not apply to them.

Such local members exist only during the execution of the method and cease to exist once the method execution is complete. They cannot be referenced from outside the method.

Since a static method belongs to a class and not to an object of that class, a static method does not execute within the context of any instance of that class. class Book{ int name; static void printName1(){ System.out.println(this.name); //will not compile System.out.println(name);//same as above. will not compile } void printName2(){ System.out.println(this.name); //this is fine. System.out.println(name); //same as above. this is fine. } } Deshmukh, Hanumant. OCP Java 17 & 21 Programmer Certification Fundamentals: Study Guide For 1Z0-829 1Z0-830 (OCP Java 17 / 21 Programmer Certification Exam Fundamentals Study Guide) (pp. 367-368). Enthuware. Kindle Edition. A common misunderstanding amongst beginners is that a static method cannot access instance fields of a class. This misunderstanding exists because they see or hear this statement in many places. However, it is an incomplete statement. The correct statement is that a static method cannot access an instance member without specifying the instance whose member it wants to access. It will be clear when you see the following code: class Book{ int name; static void printName(){ Book b1 = new Book(); Book b2 = new Book(); System.out.println(b1.name); //this will compile fine } } Deshmukh, Hanumant. OCP Java 17 & 21 Programmer Certification Fundamentals: Study Guide For 1Z0-829 1Z0-830 (OCP Java 17 / 21 Programmer Certification Exam Fundamentals Study Guide) (pp. 368-369). Enthuware. Kindle Edition.

CompletableFuture

  Welcome back to  our concurrency series ! In our first discussion, we likely touched on the traditional models of threading. Today, we’re ...