Alternative Ways to Declare Constants
There are other ways to declare constants in Java besides enums. One method is to use static final fields in a class.
class Course {
public static final String JAVA= "Java";
public static final String ANDROID= "Android";
public static final String HTML= "HTML";
public static final String CSS= "CSS";
}
We can access these constants directly by using the class name and constant name:
System.out.println(Course.JAVA); // print constant string
Output:
Java
Another method is to use an interface to declare constants:
public interface Course {
String JAVA= "Java";
String ANDROID= "Android";
String HTML= "HTML";
String CSS= "CSS";
}
We can access these constants directly by using the interface name and constant name:
System.out.println(Course.JAVA); // print constant string
Output:
Java