Page 351 - Computer_Science_F5
P. 351
Computer Science Static: The “static” keyword allows the constant to be accessed throughout the
program, meaning it can be used in multiple parts of the code.
To declare a constant in Java, the “final” keyword is used. Constant names, or identifiers,
should typically consist of nouns or noun phrases made up of multiple words.
FOR ONLINE READING ONLY
For example:
(i) Final int MAX_VALUE = 359; declares a constant named MAX_VALUE with
a value of 359.
(ii) Final int MONTHS_IN_YEAR = 12; declares a constant variable named
MONTHS_IN_YEAR with a value of 12.
Program Example 5.12:
Java program to demonstrate constant variable
public class Max {
public static final int MAX_VALUE = 359;
public static final double PI = 3.14159;
public static void main(String[] args) {
System.out.println(“The maximum value is: “ + MAX_VALUE);
System.out.println(“The value of PI is: “ + PI);
}
}
Output:
Figure 5.13: Demonstrate constant variable
(c) Types of constants
Constants can encompass various types of data that your program may use, such as:
(i) Number (int, double) - For instance, you can declare a constant like final static
int PI = 3.14159;
(ii) Text (String) - Another example is defining a constant such as final static
String INSTITUTE_NAME = “Wonderful Department at Tanzania Institute of
Education”;
342
for Advanced Secondary Schools
Computer Science Form 5.indd 342 23/07/2024 12:34

