AnyCompiler

static and final

A static field or method belongs to the class itself, not to any individual instance — every call to Counter.increment() modifies the one shared Counter.count, which is why three calls leave it at 3 rather than three separate instances each sitting at 1.

public class Main {
    static class Counter {
        static int count = 0;

        static void increment() {
            count++;
        }
    }

    public static void main(String[] args) {
        Counter.increment();
        Counter.increment();
        Counter.increment();
        System.out.println(Counter.count);
    }
}
Output
3

final

final marks something as unmodifiable after it's set. On a variable, it means the reference can never be reassigned, which is the conventional way to declare a constant in Java — PI_APPROX here can be read from anywhere but never changed.

public class Main {
    static final double PI_APPROX = 3.14159;

    public static void main(String[] args) {
        double radius = 2;
        System.out.println(PI_APPROX * radius * radius);
    }
}
Output
12.56636

Next: a closing look at Optional, and what this course covered.

Practice exercise

Define a class Counter with a static int count starting at 0 and a static method increment() that adds 1 to it. Call increment() three times, then print Counter.count.