Skip to lesson

static, final and the main Method Questions

Interviewers love three small topics: what static means, what final stops, and why main is written the way it is. They usually end with an order-of-printing puzzle, so you must be able to trace class set-up and object set-up.

Recap: static members and static blocks

A static field belongs to the class, not to any object. There is exactly one copy, shared by every object of the class, and it is reached with the class name, such as Student.count.

Instance fields get one copy per object; a static field gets one copy in total. This program counts objects with a shared counter and runs a static block once.

Example 1 · A shared counter and a static block

StaticDemo.javaJava
class Student {    static int count;                     // one copy for the whole class    static final String COLLEGE;    final String name;                    // one copy per object
    static {        System.out.println("static block runs once");        COLLEGE = "NIT Trichy";    }
    Student(String name) {        this.name = name;        count++;    }}
public class StaticDemo {    public static void main(String[] args) {        System.out.println("main starts");        new Student("Asha");        new Student("Ravi");        new Student("Meera");        System.out.println("Students: " + Student.count + " at " + Student.COLLEGE);    }}
Output
main starts
static block runs once
Students: 3 at NIT Trichy

What this code does

  • The static block prints after main starts: the class is initialised the first time it is used, by new Student("Asha"), and only once.
  • count is shared, so three constructors bring it to 3. COLLEGE is a blank static final assigned in the static block.

A static method runs without an object and cannot use this or instance fields directly. A static block, static { ... }, runs once when the class is first initialised, before any object exists.

Revise: Static variables (opens in a new tab) and Static initialization (opens in a new tab).

Predict the output

Predict the static output

Read each program and pick what it prints.

Round 1 of 3

public class Round1 {
static int total;
int mine;
Round1() {
total++;
mine++;
}
public static void main(String[] args) {
new Round1();
new Round1();
Round1 last = new Round1();
System.out.println(total + " " + last.mine);
}
}

final in three places, and final vs finally vs finalize

final stops something from changing. A final variable can be assigned only once, a final method cannot be overridden, and a final class cannot be extended.

This program shows a final variable, a final method and the unrelated finally block, which runs whether or not an exception happens.

Example 2 · final variable, final method, finally

FinalDemo.javaJava
class Fee {    static final int LATE_FINE = 50;      // constant
    final int total(int base, int daysLate) {   // cannot be overridden        return base + daysLate * LATE_FINE;    }}
public class FinalDemo {    public static void main(String[] args) {        final int base = 45000;        // base = 46000;   // error: cannot assign a value to final variable base
        Fee fee = new Fee();        try {            System.out.println("Total: " + fee.total(base, 3));            System.out.println("Ratio: " + (base / 0));        } catch (ArithmeticException e) {            System.out.println("Caught: " + e.getMessage());        } finally {            System.out.println("finally runs anyway");        }    }}
Output
Total: 45150
Caught: / by zero
finally runs anyway

What this code does

  • LATE_FINE is a constant; base cannot be reassigned; total cannot be overridden by any subclass of Fee. Three uses of final in one program.
  • finally belongs to exception handling, not to final: it runs after the catch whether or not an exception was thrown.

static final fields with fixed values are constants, written in capitals. finally is the clean-up block after try. finalize() was a method the garbage collector might call before freeing an object; it was unreliable, has been deprecated since Java 9 and is marked for removal, so use try-with-resources instead.

Revise: Final variables (opens in a new tab).

Fix the error

Fix the final error

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

The tax rate must change from 18 to 20 while the program runs.

public class Rate {
static final int TAX = 18;
public static void main(String[] args) {
TAX = 20;
System.out.println(TAX);
}
}

Error

Rate.java:4: error: cannot assign a value to final variable TAX
        TAX = 20;
        ^

Why main is public static void

A static method belongs to the class and runs without any object. It is called with the class name, such as Math.max(a, b), and it cannot use this or instance fields directly.

The JVM must start the program before any object exists. This program prints the args array and calls an overloaded main.

Example 3 · args and an overloaded main

MainDemo.javaJava
public class MainDemo {    static void main(int year) {                 // an overload, not an entry point        System.out.println("Overloaded main called with " + year);    }
    public static void main(String[] args) {     // the entry point        System.out.println("Arguments: " + args.length);        for (String a : args) {            System.out.println("arg = " + a);        }        main(2025);    }}
Output
Arguments: 0
Overloaded main called with 2025

What this code does

  • Run with no arguments, args is an empty array, so the loop does nothing. java MainDemo 2025 CSE would print two arg lines.
  • main(int) is a normal overloaded method: the JVM never calls it, but our code can.

public: the JVM calls it from outside the class. static: no object exists yet. void: nothing is returned. args holds the command-line arguments, an empty array when there are none. Main can be overloaded, but only the String[] version is the entry point; final, synchronized and String... args are all allowed. Newer Java versions (finalised in Java 25) also accept a simpler void main(), but placement interviews expect the classic signature and these reasons.

Predict the output: initialization order

An instance block is a block of code written directly in a class body, { ... }. It runs for every new object, before the constructor body, in the order the blocks appear.

Class set-up happens once; object set-up happens for every new. This program prints the order for a parent and a child class.

Example 4 · Static blocks, instance blocks and constructors

InitOrder.javaJava
class Parent {    static { System.out.println("1. Parent static block"); }    { System.out.println("Parent instance block"); }    Parent() { System.out.println("Parent constructor"); }}
class Child extends Parent {    static { System.out.println("2. Child static block"); }    { System.out.println("Child instance block"); }    Child() { System.out.println("Child constructor"); }}
public class InitOrder {    public static void main(String[] args) {        System.out.println("-- first object --");        new Child();        System.out.println("-- second object --");        new Child();    }}
Output
-- first object --
1. Parent static block
2. Child static block
Parent instance block
Parent constructor
Child instance block
Child constructor
-- second object --
Parent instance block
Parent constructor
Child instance block
Child constructor

What this code does

  • Creating the first Child initialises Parent, then Child: both static blocks run once. Then the object is built from the top: parent instance block and constructor, then the child's.
  • The second object skips the static blocks entirely, because classes are initialised only once.

Once per class: static fields and static blocks, parent before child. For each object: parent instance blocks, parent constructor, then child instance blocks, child constructor. The second object skips all static blocks.

Order of execution

Order of the first new Child()

Put the steps in the order Java runs them for the first object.

Traps: static with this, final with a mutable object

Two traps cost marks: using this in a static method, and thinking final freezes an object. This program shows the second trap with a final list.

Example 5 · Trap: final reference, mutable object

FinalReferenceTrap.javaJava
import java.util.ArrayList;import java.util.List;
public class FinalReferenceTrap {    static final List<String> TOPPERS = new ArrayList<>();    static final List<String> FIXED = List.of("Asha", "Ravi");
    public static void main(String[] args) {        TOPPERS.add("Meera");                 // allowed: the object changes        TOPPERS.add("Kiran");        // TOPPERS = new ArrayList<>();       // error: cannot assign a value to final variable TOPPERS        System.out.println(TOPPERS);
        try {            FIXED.add("Neel");        } catch (UnsupportedOperationException e) {            System.out.println("List.of cannot be changed");        }        System.out.println(FIXED);    }}
Output
[Meera, Kiran]
List.of cannot be changed
[Asha, Ravi]

What this code does

  • final stops TOPPERS from pointing to another list, but the list itself is mutable, so add works.
  • List.of creates an unmodifiable list, so add throws UnsupportedOperationException. Combine final with an unmodifiable list for a real constant.

A static method has no current object, so javac reports non-static variable this cannot be referenced from a static context. final on a reference fixes which object it points to, not the object's contents. For a truly fixed list, use List.of(...) or Collections.unmodifiableList.

Find the bug

Find the static or final bug

Each snippet has one wrong line. Tap it, then check the fix.

Add 5 to the shop's stock.

Round 1 of 3

Next step

Check your understanding

12 quick questions