Construction. Static methods

[comp1110-4F]

A static method belongs to the class itself rather than to any particular instance. It is declared with the static keyword and called on the class name rather than on an object:

public class MathUtils { public static int square(int x) { return x * x; } } // called on the class, not an instance: int result = MathUtils.square(5);

Because a static method has no associated instance, it cannot access instance fields or call instance (non-static) methods. It can only work with its arguments and other static members of the class — it is essentially a function.

Static methods are useful for utility functions that are logically associated with a class but do not depend on any particular object's state. You have already seen examples of this in the standard library, such as the utility functions for characters or array comparison.

bars magnifying-glass caret-down plus minus arrow-right xmark