Reading history

Java static and final Keywords with Examples

5 min read 0 views

Learn Java's static and final keywords: static fields and methods, static blocks, final variables, methods and classes, constants, and why a final list can still change.

Two small keywords appear in almost every Java program. static means “belongs to the class, not to any one object”: a counter shared by all students, or a helper method such as Math.max that needs no object. final means “cannot be changed”: a constant, a field set once in the constructor, a method that subclasses may not override. This lesson shows both with working examples and clears up the most common confusion about final objects.

In this lesson you will learn

  • Static fields shared by every object
  • Static methods and why they cannot use instance fields
  • Static initialisation blocks
  • Final variables, fields, methods and classes
  • Constants with static final

You should already know classes and objects.

Static Fields and Methods

public class Main {
    static class Student {
        static int count = 0;              // shared by all Student objects
        static final String SCHOOL = "Dhaka College";
        final int id;                      // set once, never changed
        String name;

        Student(String name) {
            count++;
            this.id = count;
            this.name = name;
        }

        static String schoolInfo() {       // no object needed
            return SCHOOL + " has " + count + " students";
        }
    }

    public static void main(String[] args) {
        System.out.println(Student.schoolInfo());
        Student a = new Student("Nusrat");
        Student b = new Student("Arif");
        Student c = new Student("Tania");
        System.out.println(a.name + " id=" + a.id + ", " + c.name + " id=" + c.id);
        System.out.println(Student.schoolInfo());
        System.out.println("Read through an object: " + b.count);
        System.out.println("Math.max is static too: " + Math.max(7, 12));
    }
}

Output

Dhaka College has 0 students
Nusrat id=1, Tania id=3
Dhaka College has 3 students
Read through an object: 3
Math.max is static too: 12
  • static int count exists once, for the whole Student class. Each constructor call increases the same counter, so after three objects it is 3.
  • name and id are instance fields: every object has its own copy.
  • Student.schoolInfo() is called on the class itself, even before any object exists, which is why the first line reports 0 students.
  • A static method has no this, so it cannot read name or id directly. It can use other static members such as count and SCHOOL.
  • b.count works but is misleading, because it looks like an object’s own value. Write Student.count instead.
  • Java’s own utility methods, like Math.max and Integer.parseInt, are static for the same reason: they need no object.

Static Blocks and the final Keyword

import java.util.ArrayList;
import java.util.List;

public class Main {
    static final double VAT_RATE;
    static {                                   // runs once, when the class loads
        VAT_RATE = 0.15;
        System.out.println("static block ran");
    }

    static final class MathUtil {              // final class: cannot be extended
        private MathUtil() {}                  // no objects of a utility class
        static int square(int x) { return x * x; }
    }

    public static void main(String[] args) {
        System.out.println("main started, VAT = " + VAT_RATE);
        System.out.println(MathUtil.square(9));

        final int limit = 3;
        // limit = 4;                          // compile error: cannot assign a value to final variable
        final List<String> names = new ArrayList<>();
        names.add("Rina");                     // allowed: the list itself can change
        names.add("Joya");
        // names = new ArrayList<>();          // compile error: the reference is final
        System.out.println(names + " limit=" + limit);
    }
}

Output

static block ran
main started, VAT = 0.15
81
[Rina, Joya] limit=3
  • A static { … } block runs once, when the class is first loaded, before main. It is useful for setting up static data that needs more than one line.
  • static final double VAT_RATE is a constant: one shared value that can never change. By convention constants use UPPER_SNAKE_CASE.
  • A final local variable such as limit can be assigned only once. The commented-out line would not compile.
  • final List<String> names fixes the reference, not the object. You can still add to the list, but you cannot point names at a different list. For a truly unchangeable list, use List.of(...).
  • A final class cannot be extended, and a private constructor stops anyone creating objects. Together they make a clean utility class. String is a final class.

static and final at a Glance

Applied tostaticfinal
FieldOne copy shared by the classAssigned once, then read-only
MethodCalled on the class; no thisCannot be overridden by subclasses
ClassOnly for nested classes (no outer object needed)Cannot be extended
Local variableNot allowedAssigned once
BlockRuns once when the class loadsNot applicable

Common Mistakes

  1. Calling an instance method from main without an object, which gives “non-static method cannot be referenced from a static context”. Create an object first, or make the method static.
  2. Using static fields for per-object data, so every object accidentally shares one value.
  3. Thinking final makes an object immutable. It only stops reassignment of the variable.
  4. Too much static state, which acts like global variables and makes code hard to test.

Practice Exercises

Exercise 1. Add a static method resetCount() to Student that sets the counter back to 0. Why can it not also clear every student’s name?

Show answer
static void resetCount() {
    count = 0;
}

A static method is not attached to any object, so there is no single name for it to change. It would need a reference to each Student object.

Exercise 2. Does this compile? final int[] scores = {1, 2, 3}; scores[0] = 10;

Show answer

Yes. final stops scores from pointing to another array, but the elements of the array can still change. scores = new int[3]; would not compile.

Frequently Asked Questions

Why is main declared static?

The JVM must call main before any object of your class exists. Making it static lets the JVM call it on the class directly.

What is the difference between final, finally and finalize?

final is a keyword for variables, methods and classes. finally is the block after try/catch that always runs. finalize() was an old cleanup method called by the garbage collector; it is deprecated and should not be used.

Summary

  • static members belong to the class and are shared.
  • Static methods have no this and cannot use instance fields directly.
  • final means assign once, never override, or never extend.
  • static final creates constants; a final reference can still point to a changeable object.

Next: Java Wrapper Classes and Autoboxing.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *