Keywords: current

Next: 1.9 Loose Ends Up: 1.8 The Command Pattern Previous: 1.8.2.1 A Complete Java

## 1.8.3 When to Use Static Methods

Static methods are necessary in Java for a variety or reasons including:

- defining operations on primitive types,
- defining operations on instances of library classes that cannot be modified or extended such as `String`; and
- defining operations on arrays (which we will discuss later).

For example, the `Integer` class includes a static method

    public String toString(int value);

that converts a primitive `int` value to its printable `String` form. Since `int` values are not objects, this operation cannot be formulated in object-oriented style.

Similarly, an operation

    public String squeezeWhiteSpace(String s);

that returns a `String` identical to `s` with all spaces and tabs removed must be expressed as a static method because the library `String` class cannot be modified or extended.

Finally, all operations on arrays must be expressed in static (procedural) form because array types do not have conventional class definitions; they are built-in to the Java virtual machine. We will discuss arrays in Chapter 2 when we address imperative programming in Java.