next up previous
Next: Other primitive data types Up: Unit 04 Previous: Expressions with side-effect and

Definition of constants and magic numbers

A magic number is a numeric literal that is used in the code without any explanation of its meaning. The use of magic numbers makes programs less readable and hence more difficult to maintain and update.

Example:

int salary = 20000 * workedhours;
// what is the meaning of 20000?

It is better to define symbolic names, so called constants, and use these instead of numeric literals.

// definition of a constant SALARY_PER_HOUR
final int SALARY_PER_HOUR = 20000;
...
// now it is clear what SALARY_PER_HOUR means
int salary = SALARY_PER_HOUR * workedhours;

SALARY_PER_HOUR is a constant, which in Java is a variable whose content does not change during the execution of the program. We can declare a constant by using the modifier final in the variable declaration, which indicates that the value of the variable cannot be modified (i.e., it stays constant).

The main advantages of using constants are:

Note: The declarations of constants (containing the final modifier) can be dealt with in the same way as variable declarations. Specifically, if the declaration is local to a method, the scope of the constant is the method itself. Instead, if we apply the final modifier to the declaration of an instance variable, then the constant will be associated to each object the moment it is created, and different objects may have different values for the constant.


next up previous
Next: Other primitive data types Up: Unit 04 Previous: Expressions with side-effect and