Hands on Testing Java: Lab #3

Experiment #10: Constant Declarations

Do this...
Create a test-case class named Experiment10Test.

Don't Change That Variable!

The term "variable" is deliberate: the value of a variable may vary as time goes along; it changes. However, sometimes this is not a good thing. For example, the mathematical value pi never changes.

Now Java has already declared Math.PI for us as a constant, but let's try to defy the laws of mathematics:

Math.PI = 4.0;

Since there's no data type at the front of this statement, this is an assignment statement which we'll explore in the next experiment. PI in the Math class has already been declared.

Do this...
Create a test method in Experiment10Test named testConstants(), and add the assignment statement, and compile.

Question #03.10.01 Write down the exact error message the compiler gives you.
To be answered in Exercise Questions/lab03.txt.

Fortunately, Java preserves the laws of mathematics.

Do this...
Comment out this bad code.

How can we protect our own values? Suppose we wanted to save away the value 2*pi. Normally, we'd write this:

double twoPi = 2.0 * Math.PI;

But then we could change twoPi however we like later on since it's a variable.

If we add just one more word to the declaration, we can protect the variable:

final double TWO_PI = 2.0 * Math.PI;

If you were to try changing the value of TWO_PI, the compiler would complain just as it did when we tried changing Math.PI. Both declarations use the keyword final to protect the value of the constant.

Do this...
Add the final declaration of TWO_PI to the test method, and add this assert statement:

assertEquals("two times pi", ???, TWO_PI, 1e-3);

Replace the ??? with a single literal value, compile, and run for a green bar.

You should notice that in addition to adding the word final to the declaration, we also changed the form of the identifier. We went from twoPi to TWO_PI. The former fits the convention for the identifier of a variable; the later fits the convention for the identifier of a constant.

That's what these final variables are: constants. Their values remain constant. By convention, the identifiers of Java constants are whole words, given in all upper-case letters, with underscores used to separate multiple words.

Do this...
Add error-free constant declarations for these identifiers to your test for this experiment:

Add trivial assertions that assert each of these values.

Terminology

constant