Skip to main content

Java OOP

Static Members

Complete lesson for Static Members using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Static Members

Section: Java OOP. static variables, static methods, static blocks, and static nested classes — members that belong to the class, not to each object.

What is the static keyword?

  • static marks a member that belongs to the class itself, not to any one object.
  • A static member is created once, when the class is loaded and initialized. All objects share it, and it is usable even when zero objects exist.
  • Access it with the class name: ClassName.member.
  • Real life: the school name painted on the school gate is one for all students, but every student has a different roll number. School name = static, roll number = instance.
  • Java allows static on four kinds of members (variables, methods, blocks, nested classes) plus static imports.
PlaceAllowed?ExampleMeaning
Variable (field)Yesstatic int count;One copy shared by all objects
MethodYesstatic int square(int x)Called without creating an object
BlockYesstatic { ... }Runs once when the class is initialized
Nested classYesstatic class Node { }Nested type with no link to an outer object
ImportYesimport static java.lang.Math.PI;Use static members without the class name
Top-level classNostatic class A { } at file levelCompile error: modifier static not allowed here
Local variableNostatic int x = 0; inside a methodCompile error: illegal start of expression
ConstructorNostatic Student() { }A constructor always builds an object
public class School {
    static String schoolName = "LearnCodeGuru Public School"; // one copy for all
    int rollNo;                                               // one per object
    String name;                                              // one per object

    School(int rollNo, String name) {
        this.rollNo = rollNo;
        this.name = name;
    }

    void show() {
        System.out.println(rollNo + " " + name + " - " + schoolName);
    }

    public static void main(String[] args) {
        School s1 = new School(1, "Asha");
        School s2 = new School(2, "Ravi");
        s1.show();
        s2.show();

        School.schoolName = "LCG International School"; // change it once
        s1.show();                                     // both objects
        s2.show();                                     // see the new name
    }
}

Static variable (class variable)

  • Declared with static inside the class but outside every method. Syntax: access static type name = value; for example private static int count = 0;.
  • Memory is allocated once, when the class is initialized, not every time you call new.
  • Gets a default value like instance fields: 0, 0.0, false, or null.
  • Every object reads and writes the same copy, so a change made through one object is seen by all objects.
  • Common uses: object counters, ID generators, shared settings (interest rate, tax rate), constants with static final, and caches.
  • Also called a class variable. An instance variable is also called an object variable or non-static field.
public class Visitor {
    private static int totalVisitors = 0; // shared by every Visitor
    private final String name;            // different for each Visitor

    Visitor(String name) {
        this.name = name;
        totalVisitors++;
    }

    static int getTotalVisitors() {
        return totalVisitors;
    }

    public static void main(String[] args) {
        System.out.println("Before: " + Visitor.getTotalVisitors()); // 0
        new Visitor("Asha");
        new Visitor("Ravi");
        new Visitor("Kiran");
        System.out.println("After: " + Visitor.getTotalVisitors());  // 3
    }
}

Real-life examples of static variables

  • Ask: is this value the same for every object? If yes, it can be static. If it changes per object, it must be an instance variable.
Real-life situationStatic (one value shared by all)Instance (different for each object)
College studentsCollege name, college codeStudent name, roll number, marks
Bank accountsInterest rate, bank name, IFSC prefixAccount number, holder name, balance
Company employeesCompany name, office addressEmployee id, name, salary
Cricket teamTeam name, total team scorePlayer name, runs, wickets
Website usersTotal visitors countUser name, login time
Train passengersTrain number, routePassenger name, seat number
Circles in geometryPI = 3.14159Radius of each circle
Products in a shopGST rateProduct name, price, stock
Mobile app usersApp version, server URLTheme, language, notification settings
Hostel roomsHostel name, warden phone numberRoom number, occupant names
public class SavingsAccount {
    static double interestRate = 4.0; // percent, same for every account
    private final String holder;
    private final double balance;

    SavingsAccount(String holder, double balance) {
        this.holder = holder;
        this.balance = balance;
    }

    double yearlyInterest() {
        return balance * interestRate / 100;
    }

    public static void main(String[] args) {
        SavingsAccount a = new SavingsAccount("Asha", 10000);
        SavingsAccount b = new SavingsAccount("Ravi", 50000);
        System.out.println(a.holder + ": " + a.yearlyInterest()); // 400.0
        System.out.println(b.holder + ": " + b.yearlyInterest()); // 2000.0

        SavingsAccount.interestRate = 5.0; // bank changes the rate once
        System.out.println(a.holder + ": " + a.yearlyInterest()); // 500.0
        System.out.println(b.holder + ": " + b.yearlyInterest()); // 2500.0
    }
}

Differences between instance variable and static variable

  • The key difference: one copy per object (instance) versus one copy per class (static).
PointInstance variableStatic variable
KeywordNo keywordstatic
Belongs toEach objectThe class
Number of copiesOne per objectOne per class
Memory allocatedWhen an object is created with newOnce, when the class is initialized
LifetimeUntil the object is garbage collectedUntil the class is unloaded (usually program end)
Accessed throughObject reference: obj.nameClass name: ClassName.count
Use inside a static methodOnly through an objectDirectly
Use inside an instance methodDirectlyDirectly
Default valueYes (0, false, null)Yes (0, false, null)
Other nameObject variable, non-static fieldClass variable
Typical useName, balance, roll numberCounter, constant, shared setting

Static constants: static final

  • static final means one shared copy that can never change. Name it in UPPER_SNAKE_CASE.
  • It must be assigned exactly once: at the declaration or inside a static block.
  • Compile-time constants (a primitive or String with a constant value) are copied (inlined) by javac into every class that uses them.
  • JDK examples: Math.PI, Integer.MAX_VALUE, and System.out (a static final PrintStream).
public class AppConfig {
    public static final String APP_NAME = "LearnCodeGuru";
    public static final int MAX_LOGIN_ATTEMPTS = 3;
    public static final double GST_RATE = 0.18;

    private AppConfig() { } // only constants, no objects needed

    public static void main(String[] args) {
        double price = 1000;
        System.out.println(APP_NAME + " allows " + MAX_LOGIN_ATTEMPTS + " attempts");
        System.out.println("Price with GST: " + (price + price * GST_RATE)); // 1180.0
        // GST_RATE = 0.12; // compile error: cannot assign a value to final variable
    }
}

Static method

  • Declared with static. It belongs to the class and is called as ClassName.method() without creating an object.
  • It works only with its parameters and static data, unless you pass in or create an object.
  • It cannot use this or super, because there is no current object.
  • Best for utility work whose result depends only on the inputs: Math.sqrt, Integer.parseInt, Arrays.sort, String.valueOf.
  • main is static so the JVM can call it before any object exists.
  • Real life: a calculator button for square root works the same for everyone. You do not need "your own calculator object" to press it.
public class MathUtil {
    private MathUtil() { } // utility class: no objects

    static int square(int n) {
        return n * n;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }

    static long factorial(int n) {
        long result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    static int max(int a, int b, int c) {
        return Math.max(a, Math.max(b, c));
    }

    public static void main(String[] args) {
        System.out.println(MathUtil.square(7));    // 49
        System.out.println(MathUtil.isEven(10));   // true
        System.out.println(MathUtil.factorial(5)); // 120
        System.out.println(max(4, 19, 8));         // 19 (same class: simple name works)
    }
}

Rules of static methods

  • Remember the one-line rule: static can use static directly; static needs an object to use instance members.
Inside a static method, can you...AnswerReason or workaround
Read or change a static variable?YesBoth belong to the class
Call another static method?YesBy simple name or ClassName.method()
Read an instance variable directly?NoError: non-static variable cannot be referenced from a static context. Use obj.field.
Call an instance method directly?NoCreate or receive an object, then call obj.method()
Use this or super?NoThere is no current object
Be overridden in a subclass?NoA same-signature static method in the child hides it
Be declared abstract?NoAbstract needs overriding, and static methods cannot be overridden
Be overloaded?YesDifferent parameter lists are fine
Be synchronized?YesIt locks the Class object, for example Counter.class
Be called with an object reference?Yes, but avoidThe compiler uses the reference type; it misleads readers
public class Student {
    static String college = "LCG College";
    String name = "Asha";

    static void printCollege() {
        System.out.println(college);         // OK: static uses static
        // System.out.println(name);         // ERROR: non-static variable name
        // System.out.println(this.name);    // ERROR: cannot use this in a static context
        Student s = new Student();
        System.out.println(s.name);          // OK: through an object
    }

    void printAll() {
        System.out.println(name + " - " + college); // instance method sees both
        printCollege();                             // and can call static methods
    }

    public static void main(String[] args) {
        Student.printCollege();
        new Student().printAll();
    }
}

Differences between instance method and static method

PointInstance methodStatic method
KeywordNo keywordstatic
Belongs toThe objectThe class
Call syntaxobj.method()ClassName.method()
Needs an object?YesNo
Access instance variablesDirectlyOnly through an object reference
Access static variablesDirectlyDirectly
this and superAllowedNot allowed
OverridingYes (runtime polymorphism)No (only method hiding)
BindingDynamic, at runtimeStatic, at compile time
Typical useBehaviour that depends on object state: deposit, withdrawUtilities, factories, counters: Math.max, List.of

Static block

  • static { ... } is a block that runs once, automatically, when the class is initialized.
  • It runs before main (for the main class) and before any constructor of that class.
  • Use it to initialize static variables that need logic: filling a lookup map, reading configuration, loading a native library.
  • A class may have many static blocks. They run top to bottom, together with static field initializers, in source order.
  • It cannot use this, and it cannot throw a checked exception out. An uncaught exception inside causes ExceptionInInitializerError.
import java.util.HashMap;
import java.util.Map;

public class StateCodes {
    static final Map<String, String> CODES = new HashMap<>();

    static {
        System.out.println("static block 1: loading codes");
        CODES.put("AP", "Andhra Pradesh");
        CODES.put("TS", "Telangana");
        CODES.put("KA", "Karnataka");
    }

    static {
        System.out.println("static block 2: total = " + CODES.size());
    }

    public static void main(String[] args) {
        System.out.println("main started");
        System.out.println(CODES.get("TS"));
    }
}
// Output:
// static block 1: loading codes
// static block 2: total = 3
// main started
// Telangana

Static class (static nested class)

  • Java has no static top-level class. static is allowed only on a class declared inside another class. That is called a static nested class.
  • A static nested class does not need an object of the outer class. Create it with new Outer.Nested().
  • It can use the static members of the outer class directly, even private ones. To use instance members it needs an outer object.
  • It can have its own fields, constructors, methods, and static members, like any normal class.
  • Use it to group a helper type that belongs with the outer class: Map.Entry, a linked list Node, a Builder.
  • The compiler creates a separate file for it: Outer$Nested.class.
  • Real life: a university has departments. A department record can be described without picking one particular vice-chancellor object, so it fits a static nested class.
public class University {
    private static String universityName = "LCG University";
    private String vcName = "Dr. Rao";

    static class Department {
        private final String deptName;

        Department(String deptName) {
            this.deptName = deptName;
        }

        void show() {
            System.out.println(deptName + " - " + universityName); // outer static: OK
            // System.out.println(vcName); // ERROR: needs a University object
        }

        void showVc(University u) {
            System.out.println("VC: " + u.vcName); // OK through an object
        }
    }

    public static void main(String[] args) {
        University.Department cse = new University.Department("CSE");
        Department ece = new Department("ECE"); // inside University the short name works
        cse.show();
        ece.show();
        cse.showVc(new University());
    }
}

Differences between static nested class and inner class

PointStatic nested classInner (non-static) class
Declarationstatic class Nested { } inside the outer classclass Inner { } inside the outer class
Needs an outer object?NoYes
Creating an objectnew Outer.Nested()outer.new Inner()
Access outer static membersYes, directlyYes, directly
Access outer instance membersOnly through an outer object referenceYes, directly
Hidden reference to the outer objectNoYes (Outer.this)
MemoryLighter, no leak riskKeeps the outer object alive; can leak memory
Static members inside itAllowedAllowed since Java 16 (earlier only static final constants)
JDK examplesMap.Entry, builders, list nodesIterators over the outer collection data
Prefer it whenThe nested type does not need outer object stateThe nested type works on one specific outer object
public class Outer {
    private static int shared = 10;
    private int value = 20;

    static class StaticNested {
        void show() {
            System.out.println("shared = " + shared);
        }
    }

    class Inner {
        void show() {
            System.out.println("shared = " + shared + ", value = " + value);
        }
    }

    public static void main(String[] args) {
        Outer.StaticNested a = new Outer.StaticNested(); // no Outer object needed
        a.show();

        Outer outer = new Outer();
        Outer.Inner b = outer.new Inner();               // needs an Outer object
        b.show();
    }
}

Ways to access static members

WayExampleRecommended?
Class nameMath.max(3, 7), Visitor.getTotalVisitors()Yes, the clearest way
Simple name inside the same classtotalVisitors++ inside VisitorYes
Static importimport static java.lang.Math.sqrt; then sqrt(16)Yes, for a few well-known names
Object referencev1.getTotalVisitors()No, it compiles with a warning and looks like instance data
null referenceVisitor v = null; v.getTotalVisitors();It works (no NullPointerException) but is confusing. Never do this.
import static java.lang.Math.PI;
import static java.lang.Math.pow;
import static java.lang.Math.sqrt;

public class Circle {
    public static void main(String[] args) {
        double r = 5;
        System.out.println("Area = " + PI * pow(r, 2)); // no Math. prefix
        System.out.println("sqrt(81) = " + sqrt(81));
    }
}

When to use static and when not to

Use static forAvoid static for
Constants: static final double GST_RATEData that belongs to one object: name, balance, marks
Pure utility methods: MathUtil.squareBehaviour that differs per object or per subclass
Factory methods: Color.ofRgb, List.ofMutable global state shared across threads and tests
Object counters and ID generatorsAvoiding the work of passing an object as a parameter
Helper nested types: Node, Builder, EntryCode you need to mock, replace, or override in tests
The program entry point: mainLarge static collections that keep growing (memory leaks)
L2

Advanced — Static Members

How static members live in memory

  • When the JVM loads a class it creates one Class object and one set of static fields for that class. Since Java 8 static fields are stored in the heap with the class mirror, and class metadata such as method bytecode lives in Metaspace.
  • Each new creates an object on the heap that holds only instance fields. Static fields are never copied into objects.
  • So 1000 Student objects mean 1000 copies of name but only one copy of college. That is a memory saving.
  • Strictly, a static field is one copy per class per class loader. Application servers that load the same class twice get two copies.
ItemWhere it livesHow many copies
Instance fieldInside each object on the heapOne per object
Static fieldWith the class (heap, Class mirror)One per class (per class loader)
Local variable / parameterThread stack frameOne per method call
Method bytecode (static or instance)Metaspace (class metadata)One per class

Class loading and initialization order

  • A class is initialized on its first active use: new, calling a static method, reading or writing a non-constant static field, Class.forName, or being the main class.
  • It is not initialized by: declaring a variable of that type, reading a compile-time static final constant, or creating an array like new Demo[5].
  • Order: parent static init, then child static init (once only). Then for every new: parent instance blocks and constructor, then child instance blocks and constructor.
class Parent {
    static { System.out.println("1. Parent static block"); }
    { System.out.println("3. Parent instance block"); }
    Parent() { System.out.println("4. Parent constructor"); }
}

class Child extends Parent {
    static { System.out.println("2. Child static block"); }
    { System.out.println("5. Child instance block"); }
    Child() { System.out.println("6. Child constructor"); }
}

public class InitOrder {
    public static void main(String[] args) {
        new Child();
        System.out.println("--- second object ---");
        new Child(); // static blocks do NOT run again: only 3, 4, 5, 6
    }
}

Method hiding: static methods are not overridden

  • If a child class declares a static method with the same signature as a parent static method, it hides the parent method.
  • Which version runs is decided at compile time by the reference type, not by the object type.
  • Putting @Override on a static method is a compile error. A static method cannot hide an instance method, and an instance method cannot override a static one (both are compile errors).
class Animal {
    static void info() { System.out.println("Animal static info"); }
    void sound() { System.out.println("Animal sound"); }
}

class Dog extends Animal {
    static void info() { System.out.println("Dog static info"); } // hides

    @Override
    void sound() { System.out.println("Dog barks"); }              // overrides
}

public class HidingDemo {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.info();   // Animal static info (reference type decides)
        a.sound();  // Dog barks          (object type decides)
        Dog.info(); // Dog static info
    }
}

Static nested class in practice: the Builder pattern

  • A builder collects optional settings step by step and then creates an immutable object.
  • It is a static nested class because building a pizza must not require an existing pizza object.
  • The outer constructor is private, so Pizza.Builder is the only way to create a Pizza.
public class Pizza {
    private final String size;
    private final boolean cheese;
    private final boolean olives;

    private Pizza(Builder b) {
        this.size = b.size;
        this.cheese = b.cheese;
        this.olives = b.olives;
    }

    @Override
    public String toString() {
        return size + " pizza, cheese=" + cheese + ", olives=" + olives;
    }

    public static class Builder {
        private final String size;
        private boolean cheese;
        private boolean olives;

        public Builder(String size) { this.size = size; }
        public Builder cheese() { cheese = true; return this; }
        public Builder olives() { olives = true; return this; }
        public Pizza build() { return new Pizza(this); }
    }

    public static void main(String[] args) {
        Pizza p = new Pizza.Builder("Large").cheese().olives().build();
        System.out.println(p); // Large pizza, cheese=true, olives=true
    }
}

Static factory methods

  • A static factory is a static method that returns an object instead of making callers use new directly.
  • Benefits: meaningful names (ofGray), caching and reuse (Integer.valueOf, Boolean.valueOf), and the freedom to return a subtype (List.of).
  • Often combined with a private constructor so all creation goes through the factories.
public class Color {
    private static final Color RED = new Color(255, 0, 0);
    private final int r, g, b;

    private Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    static Color red() { return RED; } // cached: same object every time
    static Color ofRgb(int r, int g, int b) { return new Color(r, g, b); }
    static Color ofGray(int level) { return new Color(level, level, level); }

    @Override
    public String toString() { return "rgb(" + r + "," + g + "," + b + ")"; }

    public static void main(String[] args) {
        System.out.println(Color.red());                // rgb(255,0,0)
        System.out.println(Color.ofGray(128));          // rgb(128,128,128)
        System.out.println(Color.red() == Color.red()); // true
    }
}

Lazy singleton with a static holder class

  • A private static nested class is not initialized until it is first used.
  • The JVM initializes classes under a lock, so this gives a thread-safe, lazy singleton without synchronized code.
public class Logger {
    private Logger() {
        System.out.println("Logger created");
    }

    private static class Holder {
        static final Logger INSTANCE = new Logger();
    }

    public static Logger getInstance() {
        return Holder.INSTANCE; // Holder is initialized on the first call only
    }

    void log(String msg) {
        System.out.println("[LOG] " + msg);
    }

    public static void main(String[] args) {
        System.out.println("app started");               // printed before "Logger created"
        Logger.getInstance().log("first");
        Logger.getInstance().log("second");
        System.out.println(Logger.getInstance() == Logger.getInstance()); // true
    }
}

Static variables and thread safety

  • A static variable is shared by every thread. count++ is read, add, write, so two threads can lose updates.
  • Fixes: AtomicInteger, a synchronized static method (locks ClassName.class), or avoid shared mutable static state.
  • Static initialization itself is thread-safe, but later changes to static fields are not.
import java.util.concurrent.atomic.AtomicInteger;

public class TicketCounter {
    private static int unsafeCount = 0;
    private static final AtomicInteger safeCount = new AtomicInteger();

    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            for (int i = 0; i < 10_000; i++) {
                unsafeCount++;               // race condition
                safeCount.incrementAndGet(); // atomic
            }
        };
        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("unsafe = " + unsafeCount);   // often less than 20000
        System.out.println("safe   = " + safeCount.get()); // always 20000
    }
}

static in interfaces, enums, and records

  • Interface fields are implicitly public static final. Since Java 8 interfaces can have static methods, called only as InterfaceName.method() and not inherited by implementing classes.
  • Enum constants are public static final objects, and values() and valueOf() are static methods.
  • Records can have static fields and static methods, but no extra instance fields.
  • Nested interfaces, enums, and records are implicitly static.
interface Validator {
    int MIN_LENGTH = 8; // implicitly public static final

    static boolean isStrong(String password) {
        return password.length() >= MIN_LENGTH
            && password.chars().anyMatch(Character::isDigit);
    }
}

record Point(int x, int y) {
    static final Point ORIGIN = new Point(0, 0);

    static Point of(int x, int y) {
        return new Point(x, y);
    }
}

public class StaticEverywhere {
    public static void main(String[] args) {
        System.out.println(Validator.isStrong("learn2code")); // true
        System.out.println(Point.ORIGIN);                     // Point[x=0, y=0]
        System.out.println(Point.of(3, 4));                   // Point[x=3, y=4]
    }
}

Common static pitfalls

PitfallWhat goes wrongFix
Mutable public static fieldAny code can change it; hidden couplingMake it private with methods, or final
Static collection that only growsMemory leak: it lives until the class unloadsClear it, bound it, or use a cache with eviction
Calling a static method through an objectReaders think it is per-object behaviourAlways call through the class name
Static state in unit testsTests pass alone but fail when run togetherReset in @BeforeEach or remove the static
Static method that needs different behaviourIt cannot be overridden or easily mockedUse an instance method behind an interface
Using an instance field inside mainCompile error: non-static from a static contextCreate an object first, then use obj.field
Exception in a static blockExceptionInInitializerError, then NoClassDefFoundError on later useHandle errors inside the block and fail with a clear message
L3

Tricky Interview Points

Q1) What is the static keyword in Java?

Answer It marks a member that belongs to the class instead of to each object. static can be applied to variables, methods, blocks, nested classes, and imports.

Q2) What is a static variable? Give a real-life example.

Answer A class variable with one shared copy for all objects, created when the class is initialized. Example: the college name for all students, or the interest rate for all savings accounts.

Q3) What is the difference between a static variable and an instance variable?

Answer A static variable has one copy per class and is accessed by class name. An instance variable has one copy per object and is accessed through an object reference.

Q4) Can a static method access instance variables?

Answer Not directly, because it has no current object. It can use them only through an object reference that is passed in or created inside the method.

Q5) Why can we not use this or super inside a static method?

Answer this and super refer to the current object. A static method runs without any object, so there is nothing for them to refer to.

Q6) Can we override a static method?

Answer No. A child static method with the same signature hides the parent method. The call is resolved at compile time using the reference type, so there is no runtime polymorphism.

Q7) Can static methods be overloaded?

Answer Yes. Overloading only needs a different parameter list, and it is resolved at compile time, so static methods can be overloaded freely.

Q8) Why is main static? What happens if we remove static?

Answer The launcher must call main before any object exists, so it calls it by class name. Without static, older Java versions compile the class but the launcher fails with an error saying main is not static. Java 25 added instance main methods (JEP 512) as a feature for small programs, but public static void main remains the standard form.

Q9) When does a static block run? Can a class have more than one?

Answer Once, when the class is initialized on first active use. A class can have many static blocks; they run in source order together with static field initializers.

Q10) Can we run a program without main by using a static block?

Answer Only in Java 6 and earlier. Since Java 7 the launcher checks for main before initializing the class, so it reports that the main method is missing.

Q11) Can a top-level class be static?

Answer No. static is allowed only on nested classes. A top-level class marked static is a compile error.

Q12) What is a static nested class, and how is it different from an inner class?

Answer A static nested class does not need an outer object and has no hidden outer reference. An inner class needs an outer object, can use its instance fields directly, and keeps it alive through Outer.this.

Q13) How do you create an object of a static nested class?

Answer With new Outer.Nested(). Inside the outer class you can write new Nested(). For an inner class you need outer.new Inner().

Q14) Can a static nested class access private members of the outer class?

Answer Yes. It can access outer static members directly, even private ones. It can access private instance members only through a reference to an outer object.

Q15) Can a local variable or a constructor be static?

Answer No. Local variables live in a method call stack frame, and constructors always build an object. Both are compile errors with static.

Q16) Can an abstract method be static?

Answer No. An abstract method must be overridden, and static methods cannot be overridden, so abstract static is a compile error.

Q17) Are static variables thread-safe?

Answer No. They are shared by all threads. Changes like count++ need AtomicInteger, synchronization, or a design without shared mutable static state.

Q18) What happens if you call a static method using a null reference?

Answer It runs normally without a NullPointerException, because the compiler uses only the reference type. It is legal but very confusing.

Q19) What is a static import?

Answer import static lets you use static members without the class name, for example import static java.lang.Math.PI. Use it for a few well-known names only.

Q20) Where are static variables stored in memory?

Answer Since Java 8 they are stored in the heap together with the Class object of their class. Class metadata such as method bytecode is in Metaspace.

Q21) What is ExceptionInInitializerError?

Answer It is thrown when a static initializer or static field initializer throws an exception. Later attempts to use that class fail with NoClassDefFoundError.

L4

Simple Programs

Employee ID generator with a shared company name

public class Employee {
    static final String COMPANY = "LearnCodeGuru Pvt Ltd";
    private static int nextId = 1001;

    private final int id;
    private final String name;

    Employee(String name) {
        this.id = nextId++;
        this.name = name;
    }

    static int employeesCreated() {
        return nextId - 1001;
    }

    void print() {
        System.out.println(id + " " + name + " @ " + COMPANY);
    }

    public static void main(String[] args) {
        new Employee("Asha").print();  // 1001 Asha @ LearnCodeGuru Pvt Ltd
        new Employee("Ravi").print();  // 1002 Ravi @ ...
        new Employee("Kiran").print(); // 1003 Kiran @ ...
        System.out.println("Total: " + Employee.employeesCreated()); // 3
    }
}

Class topper using static variables

public class Result {
    private static String topperName = "none";
    private static int topperMarks = -1;

    private final String name;
    private final int marks;

    Result(String name, int marks) {
        this.name = name;
        this.marks = marks;
        if (marks > topperMarks) {
            topperMarks = marks;
            topperName = name;
        }
    }

    static void printTopper() {
        System.out.println("Topper: " + topperName + " (" + topperMarks + ")");
    }

    public static void main(String[] args) {
        new Result("Asha", 87);
        new Result("Ravi", 93);
        new Result("Kiran", 78);
        Result.printTopper(); // Topper: Ravi (93)
    }
}

Temperature converter utility class

public final class TempConverter {
    private TempConverter() { } // no objects

    static double toFahrenheit(double celsius) {
        return celsius * 9 / 5 + 32;
    }

    static double toCelsius(double fahrenheit) {
        return (fahrenheit - 32) * 5 / 9;
    }

    static double toKelvin(double celsius) {
        return celsius + 273.15;
    }

    public static void main(String[] args) {
        System.out.println(TempConverter.toFahrenheit(100)); // 212.0
        System.out.println(TempConverter.toCelsius(212));    // 100.0
        System.out.println(TempConverter.toKelvin(0));       // 273.15
    }
}

Overloaded static methods: Calculator

public class Calculator {
    static int add(int a, int b) {
        return a + b;
    }

    static double add(double a, double b) {
        return a + b;
    }

    static int add(int... nums) {
        int sum = 0;
        for (int n : nums) {
            sum += n;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(Calculator.add(2, 3));        // 5   (int, int)
        System.out.println(Calculator.add(2.5, 3.5));    // 6.0 (double, double)
        System.out.println(Calculator.add(1, 2, 3, 4));  // 10  (varargs)
    }
}

Static nested class: linked list Node

public class MyLinkedList {
    private static class Node {
        int data;
        Node next;

        Node(int data) {
            this.data = data;
        }
    }

    private Node head;
    private static int listsCreated = 0;

    MyLinkedList() {
        listsCreated++;
    }

    void addFirst(int value) {
        Node n = new Node(value);
        n.next = head;
        head = n;
    }

    void print() {
        for (Node cur = head; cur != null; cur = cur.next) {
            System.out.print(cur.data + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        MyLinkedList list = new MyLinkedList();
        list.addFirst(30);
        list.addFirst(20);
        list.addFirst(10);
        list.print();                                   // 10 20 30
        System.out.println("lists = " + listsCreated);  // 1
    }
}

Static nested class returning two values: MinMax

public class Stats {
    static class MinMax {
        final int min;
        final int max;

        MinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }
    }

    static MinMax findMinMax(int[] values) {
        int min = values[0];
        int max = values[0];
        for (int v : values) {
            if (v < min) min = v;
            if (v > max) max = v;
        }
        return new MinMax(min, max);
    }

    public static void main(String[] args) {
        Stats.MinMax r = Stats.findMinMax(new int[] {42, 7, 19, 88, 3});
        System.out.println("min = " + r.min + ", max = " + r.max); // min = 3, max = 88
    }
}

Predict the output: static vs instance counter

public class CounterDemo {
    static int staticCount = 0;
    int instanceCount = 0;

    CounterDemo() {
        staticCount++;
        instanceCount++;
    }

    public static void main(String[] args) {
        CounterDemo a = new CounterDemo();
        CounterDemo b = new CounterDemo();
        CounterDemo c = new CounterDemo();

        System.out.println(a.instanceCount + " " + b.instanceCount + " " + c.instanceCount); // 1 1 1
        System.out.println(CounterDemo.staticCount);                                         // 3
    }
}
L5

Problem Solving Tricks

  • One-line rule: static can use static directly; static needs an object to use instance members.
  • Ask "is this value the same for every object?" If yes, it can be static. If no, it must be an instance variable.
  • Always call static members through the class name, never through an object reference.
  • public static final constants use UPPER_SNAKE_CASE: MAX_SIZE, GST_RATE.
  • Utility classes: final class, private constructor, only static methods (like Math and Collections).
  • Make a nested class static by default. Remove static only when it truly needs the outer object.
  • Static methods hide, instance methods override. @Override on a static method will not compile.
  • Keep mutable static fields private, and use AtomicInteger or synchronization when threads share them.
  • A static block runs once per class, not once per object. Instance blocks run on every new.
  • Unit tests must not depend on leftover static state. Reset it in @BeforeEach or avoid the static.
L6

Practice Programs List

  1. Count how many objects of a Car class were created using a static variable.
  2. Create a Student class where the college name is static and roll numbers are generated automatically from a static counter.
  3. Write a SavingsAccount class with a static interest rate. Change the rate once and print the interest for three accounts.
  4. Write a utility class StringUtil with static methods reverse, isPalindrome, and countVowels.
  5. Write static int gcd(int a, int b) and static int lcm(int a, int b) and call them without creating an object.
  6. Add two static blocks and a constructor to a class, create two objects, and confirm the blocks run once.
  7. Inside a static method, try to use an instance field and this. Write down the exact compiler errors.
  8. Show method hiding: Parent and Child both have static void hello(). Call it through a Parent reference holding a Child object.
  9. Create a static nested class Address inside Customer and create it from main with new Customer.Address(...).
  10. Rewrite the same nested class as an inner class and compare how objects are created.
  11. Build a Pizza or Laptop class with a static nested Builder.
  12. Implement a lazy singleton Config with a private static holder class and prove only one object is created.
  13. Run two threads that increment a static int 10,000 times each. Then fix it with AtomicInteger.
  14. Use static imports for Math.PI, Math.pow, and Math.sqrt in a circle and hypotenuse program.