Wednesday, July 24, 2013

Fixing the Value of a Variable

Sometimes you will declare and initialize a variable with a value that should never change. For example:

int feet_per_yard = 3;
double mm_per_inch = 25.4;

Both these values should be fixed. There are always 3 feet to a yard, and an inch will always be 25.4 millimeters. Although they are fixed values for which you could use a literal in calculations, it is very convenient to store them in a variable because using suitable names makes it clear in your program what they mean. If you use the value 3 in your program code it could mean anything - but the name feet_per_yard leaves no doubt as to what it is.

However, ideally you’d like to prevent these variables from varying if possible. Accidental changes to the number of feet in a yard could make the results of your program suspect to say the least. Java provides you with a way to fix the value of any variable by using the final keyword when you declare it. For example:

final int FEET_PER_YARD = 3; // Constant values
final double MM_PER_INCH = 25.4; // that cannot be changed

The final keyword specifies that the value of a variable is final and must not be changed. The compiler will check your code for any violations of this and flag them as errors. I’ve used uppercase letters for the names of the variables here because it is a convention in Java to write constants in this way. This makes it easy to see which variables are defined as constant values. Obviously, any variable you declare as final must have an initial value assigned, as you can’t specify it later.

Now that you know how to declare and initialize variables of the basic types, you are nearly ready to write a program. You just need to look at how you express the calculations you want carried out, and you store the results.

No comments:

Post a Comment

Thanks for Commenting......