Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Constants
-
A value that does not change during the execution of the program.
-
Mark these with the keyword final.
-
Normally, final variable names are upper case.
-
They are commonly used for things that do not change, like the number of
bits in a byte, the value of pi, etc. Also, they can be used to identify
types of things.
-
For example, you might have a class, Car, that has a number of final variables.
One might be named CHEVETTE and have an arbitrary int value of 6.
Then, when you make a car object, you assign the int value of this constant
to another variable called type. Finally, you can test the car object
like so:
(Corrected 1/18/2002. Previous version had a single =, which is incorrect
and would not compile.)
if (myCar.type == Car.CHEVETTE) {
System.out.println("I drive a Chevette!");
}
-
To declare that constant in the car class:
final int CHEVETTE = 6;
-
Many times finals are also static. But we'll get in to this later.
-
They are also often given public access, which means that other classes
can access them. That would make sense, because constants (like
Math.PI) often exist for use in other classes.
Operators
Created by: Brandan
Jones January 4, 2002