Static members, static block, static class

static members belong to the class itself: one shared totalBooks counter, methods callable without objects, a block that runs once at class load, and the nested-only static class rule.

11 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

A number that belongs to nobody

The librarian wants one line on the dashboard:

Total books in library: 6000

Where does that number live? Not inside any single Book: each object knows its own title and copies, and no book is responsible for counting its 5999 colleagues. The total belongs to the collection as a whole, that is, to the class.

Java has a home for exactly such data: static members, the ones marked "belongs to the class, not to any object".

Theory

Diaries and the notice board

Every member of a hostel keeps a personal diary: your entries are yours alone. That is an instance field: one copy per object.

The hostel also has one notice board in the corridor: a single copy, everyone reads and updates the same one. That is a static field. Pin "total residents: 94" on the board, and there is no confusion about whose number it is: it is the hostel's.

Theory

The static family, formally

Static field: one copy for the entire class, shared by every object. static int totalBooks;

Static method: called on the class itself, Book.resetCatalog(), no object needed. Inside it there is no this, so it cannot touch instance fields directly.

Static block: static { ... } runs exactly once, when the JVM first loads the class, before any object or even main's first use.

Static class: only a class nested inside another may be static; a top-level static class does not compile.

Practical

The shared counter

class Book {
    static int totalBooks = 0;   // ONE copy, on the notice board
    String title;                // per-object, in each diary

    static {                     // runs once, at class load
        System.out.println("Book catalog initialised");
    }

    Book(String t) {
        title = t;
        totalBooks++;            // every birth ticks the shared counter
    }
}

public class BookBridge {
    public static void main(String[] args) {
        new Book("Let Us C");
        new Book("Java Complete Reference");
        new Book("Data Structures");
        System.out.println("Total books: " + Book.totalBooks);
    }
}

Think first

Trace the counter

Run the listing in your head, line by line. Before tapping: exactly what prints, in what order, and why does the first line appear at all?

Show the answer

First Book catalog initialised: the static block fires when the class loads, triggered by the first new Book, before any constructor body. Then 3 constructors each run totalBooks++ on the SAME shared field: 0 to 1 to 2 to 3. Finally Total books: 3. Had totalBooks been an instance field, each book would privately count 1 and no total would exist anywhere: that one-shared-copy behaviour is the whole point of static.

Quiz

How many times does a static block execute?

  1. Once for every object created
  2. Once, when the class is first loaded
  3. Every time a static method is called
  4. Never, unless called explicitly
Show the answer

Once, when the class is first loaded

The static block belongs to the class, so it runs at class-loading time, exactly once per program run, even if you then create 6000 Books or none after the load. Option A describes a constructor's rhythm, the classic confusion. Options C and D invent triggers that do not exist: nobody calls a static block; the JVM runs it unprompted. Exam phrasing to remember: constructor = once per object, static block = once per class.

Watch out

The rules static breaks if you let it

No this, no instance fields: inside a static method there is no current object, so this and direct use of title are compile errors. This is precisely why last lesson said this cannot appear in main.

Top-level static class: static class Book at file level does not compile; static applies only to nested classes.

b1.totalBooks compiles but reads like an instance field and misleads readers: always write Book.totalBooks.

Theory

You have used static all along

public static void main: static so the JVM can start the program without constructing any object first; that mysterious word from your very first listing now has a meaning. Math.sqrt(16), Integer.parseInt("42"): static methods, called on classes, no new anywhere. And the pattern here, one shared counter ticked in the constructor, is a standard exam program: practise writing it from a blank page.

Summary

Key takeaways

  • static = belongs to the class: one shared copy, not one per object.
  • Static methods run without an object; no this, no direct instance access inside them.
  • A static block runs exactly once, at class load; constructors run once per object.
  • Only nested classes may be static; top-level static classes do not compile.
  • Access as ClassName.member: Book.totalBooks, Math.sqrt.
  • main is static so the JVM needs no object to begin.
  • Memory hook: diary per object, one notice board per class.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Classes and Objects

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Static members, static block, static class · Java Programming Language · Gri-Learn