Using constants

There are certain values which, when a program is run, will not change but will impact the running of the program. The classic example is maths constants such as PI.

final float pi = 3.14f;

This will identify pi for the rest of the program. The final prefix will stop the value from being changed. We could then use it later, for example a = pi * (r * r) to get the area of a circle. Using constants in this way makes code much more maintainable as there is only one place where it needs to be changed. So if we wanted to add more precision to pi we only have to do it once.

Another example could be to allow finer control over a program for other developers. Consider a program which allows you to input famous quotes and email them to your friends. You may wish to limit the number of quotes you send so you do not annoy them too much! So we could write

final int NUMEBR_OF_QUOTES_TO_SEND = 6;

Notice the painfully obvious identifier! This is very common for constants as they they tend to have a major impact to the working of the code. It also makes the code more readable as there will be little debate over the meaning of this constant!