Constants and Enumerations in Java
In Java, constants and enumerations are similar to how they are used in other programming languages.
A constant is a value that cannot be changed or modified once it has been set. In Java, constants are typically represented using the final
keyword. For example:
final int PI = 3.14159265;
In this example, PI
is a constant with the value of pi. The final
keyword indicates that the value of PI
cannot be changed.
An enumeration, on the other hand, is a data type that consists of a set of named values, called elements or members. In Java, enumerations are defined using the enum
keyword. For example:
enum Color {
RED, GREEN, BLUE
}
In this example, Color
is an enumeration with three members: RED
, GREEN
, and BLUE
. The members of the Color
enumeration are constants themselves, and they are given meaningful names to make the code easier to read and understand.
Here is an example of how constants and enumerations can be used in a Java program:
final int PI = 3.14159265;
enum Color {
RED, GREEN, BLUE
}
public class Main {
public static void main(String[] args) {
System.out.println(PI);
System.out.println(Color.RED);
}
}
In this example, the constant PI
is printed to the console, as well as the value of the RED
member of the Color
enumeration