In Java, constants are variables whose values cannot be changed once they have been assigned. They are typically used to store fixed values that are used throughout a program, such as mathematical constants, configuration values, or other unchanging data.
Constants in Java are defined using the final keyword. The final keyword ensures that the variable can be assigned only once. By convention, constant names are written in uppercase letters with underscores separating words.
To declare a constant, use the final keyword followed by the type of the variable, the variable name, and the value. Constants can be declared at different levels, such as within a class, an interface, or a method.
public class ConstantsExample {
// Class-level constants
public static final double PI = 3.14159;
public static final String APP_NAME = "MyApplication";
public static void main(String[] args) {
// Local constant
final int MAX_USERS = 100;
// Use the constants
System.out.println("Value of PI: " + PI);
System.out.println("Application Name: " + APP_NAME);
System.out.println("Max Users: " + MAX_USERS);
// Uncommenting the following line would cause a compilation error
// PI = 3.14; // Error: cannot assign a value to final variable PI
}
}
Constants are typically used for values that are meant to remain unchanged throughout the life of a program, such as configuration values, default settings, or fixed mathematical values.
public class Circle {
// Define a constant for PI
public static final double PI = 3.14159;
// Method to calculate the area of a circle
public static double calculateArea(double radius) {
return PI * radius * radius;
}
public static void main(String[] args) {
double radius = 5.0;
double area = calculateArea(radius);
System.out.println("Area of the circle: " + area);
}
}
In Java, all variables declared in an interface are implicitly public, static, and final. This means they are constants by definition.
public interface AppConfig {
String APP_NAME = "MyApplication";
int MAX_USERS = 100;
}
public class Main {
public static void main(String[] args) {
System.out.println("Application Name: " + AppConfig.APP_NAME);
System.out.println("Max Users: " + AppConfig.MAX_USERS);
}
}