Replace Magic Number with Symbolic Constant

You have a literal number with a particular meaning.

Create a constant, name it after the meaning, and replace the number with it.

double potentialEnergy(double mass, double height) {
  return mass * height * 9.81;
}

image/svg+xml

double potentialEnergy(double mass, double height) {
  return mass * GRAVITATIONAL_CONSTANT * height;
}
static final double GRAVITATIONAL_CONSTANT = 9.81;

Additions

Using a constant method

For this refactoring I used a symbolic constant, which is the most common Java idiom.

However Jutta Eckstein reminded me that an alternative is the constant method, which is a method of this form

public static double gravitationalConstant() {
	return 9.81;
}

This idiom is less familiar to C based programmers, but is very familiar to Smalltalkers (who didn't have constants in their language). On the whole I don't tend to use this in Java as it is less idiomatic to the language. However if you need to replace the simple return with a calculated value then it's worth changing the constant field to a constant method. (I guess there should be a refactoring for that....)