AP Computer Science Java: Lesson 1.3c
Variables and Constants - Working with Constants


Lesson 1.3c - Working with Constants
Purpose: To learn how to declare and assign values to Java constants

Declaring constants
Sometimes programmers have the need to store a value which will never or very rarely change. A variable, by its nature, is allowed to be changed. So a variable is not the right choice for this data storage. Instead, programmers use a different type of storage device called a constant.

A constant declaration is just like a variable declaration with the addition of the Java keyword final.

final type name = value;

Here are some examples:

final int CURRENT_YEAR = 2006;
final double SALES_TAX_RATE = 0.0725;
final String ERROR_MSG = "Invalid Input";

Note the use of all capital letters in the names of constants as well as the underscore between words in the name. Recall that these are Java conventions.


Using constants
We can also use declared constants in equations and output, just like variables.

Examples
double tax = price * SALES_TAX_RATE;
System.out.println("Error: " + ERROR_MSG);


Why are constants important?
Good question. Here are some reasons.

1. The keyword final does not allow the value of the constant to be changed after it has been declared. Any attempt to reassign the value of a constant is met with a compiler error. This protects the value so that it is not accidentally changed during the course of the program. Declared variables do not have this feature.

2. The use of a constant allows for global changes to its value in just one place - the constant declaration. Imagine that a program for a cash register has to use the sales tax rate in many places throughout the program. If the programmer types the actual number of the sales tax rate in all of those places, making changes to that value would require searching for every occurrence. However, if that value was stored in a constant, the programmer can simply change the value in the constant declaration which will automatically update that value everywhere that constant is named in the program.

Does every program require constants?
No. Only use constants as needed - when a value needs to be fixed throughout the program.

 

© DanShuster.com