What does the keyword static mean on a method or field?
Options
- It cannot be changed after its first assignment
- It belongs to the class, so no instance is needed (Correct option)
- It is only visible inside the same source file
- It runs automatically when the program starts up
Answer
It belongs to the class itself, not to any single object, and you can use it without creating an instance
Why
Normal (instance) fields and methods belong to each object: every new Person() has its own name.
A static member belongs to the class: there is only one copy, shared by all objects, and you call it as ClassName.method() without new. Math.max(1, 2) and main are static.
Careful: static mutable fields are shared state, which is a classic source of bugs in multi-threaded programs.
Remember
static = one copy per class, not per object.