JAVA Tutorial



CONSTANTS IN JAVA


🔸 Constants in Java

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.

🔹 Declaring Constants

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;
  

🔸 Example: Constant Declaration

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);
  }
}
  

🔹 Constant Naming Convention

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
  

🔸 Example: Using Constants in Java

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);
  }
}
  

🔸 Rules for Constants in Java

  • The final keyword is used to declare a constant.
  • Constants must be initialized when they are declared; their value cannot be changed afterward.
  • It is recommended to use uppercase letters for constant names, with words separated by underscores.
  • Constants can be of any data type (e.g., int, double, char, etc.).
  • Constants can be declared both at the class level (static constants) and within methods (local constants).

🔸 Static Constants

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");
  }
}
  
💡 Tip: Once a constant is declared with the final keyword, its value cannot be changed, making it useful for fixed values like mathematical constants or configuration values.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review