In Java, a constant is a variable whose value cannot be changed after it is initialized. Constants are used to store values that should remain constant throughout the execution of the program. Constants are declared using the final
keyword, which ensures that the variable's value cannot be modified once assigned.
To declare a constant in Java, you need to use the final
keyword followed by the data type and variable name. It is also a convention to use uppercase letters for constant names.
// Syntax to declare a constant in Java final dataType CONSTANT_NAME = value;
public class ConstantExample { public static void main(String[] args) { final int MAX_SPEED = 120; // Declare a constant for maximum speed System.out.println("The maximum speed is: " + MAX_SPEED); } }
In Java, it is a convention to write constant names in uppercase letters with words separated by underscores. This helps distinguish constants from regular variables and enhances code readability.
// Example of a constant with proper naming convention final double PI = 3.14159; // The value of Pi
public class AreaCalculator { public static void main(String[] args) { final double PI = 3.14159; // Declare constant for Pi final double radius = 7; // Declare constant for radius double area = PI * radius * radius; // Use constant in the area calculation System.out.println("The area of the circle is: " + area); } }
final
keyword is used to declare a constant.int
, double
, char
, etc.).Constants can also be declared as static if they are intended to be shared across all instances of a class. Static constants are typically declared at the class level and are accessible without creating an object of the class.
public class StaticConstantExample { // Static constant static final double EARTH_RADIUS = 6371; // Radius of Earth in kilometers public static void main(String[] args) { System.out.println("The radius of Earth is: " + EARTH_RADIUS + " km"); } }
final
keyword, its value cannot be changed, making it useful for fixed values like mathematical constants or configuration values.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!