Lesson 30 of 34

static and final

8 min 35 XP

A static field is shared by all objects, with just one copy, for example to count how many objects were created. Call a static method without an object as ClassName.method(). A final value can't be changed.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

Why is main() static? The JVM must call it before any object exists. A popular interview question.

Challenge

+35 XP

Write class Counter with a static int total and its own int value per object. increment() adds 1 to both. In main(), read n, create two Counters, increment the first n times and the second twice, then print: Input: 3 Output: A: 3 B: 2 Total: 5

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.