> For the complete documentation index, see [llms.txt](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://muhammad-tri-wibowo.gitbook.io/java-tutorials/basic-java/constant.md).

# Constant

In Java, constants are variables whose values should not be altered once they are assigned. Constants are declared using the `final` keyword, which indicates that the value of the variable cannot be changed after initialization. Constants are often used for values that should remain fixed throughout the program, such as mathematical constants, configuration settings, or predefined limits.

#### Declaring Constants:

**Syntax:**

```java
final data_type CONSTANT_NAME = value;
```

**Example:**

```java
public class ConstantsExample {
    final double PI = 3.14159;
    final int MAX_SIZE = 100;

    public static void main(String[] args) {
        ConstantsExample example = new ConstantsExample();
        System.out.println("PI Value: " + example.PI);
        System.out.println("Maximum Size: " + example.MAX_SIZE);
    }
}
```

**Explanation:**

In this example, `PI` and `MAX_SIZE` are declared as constants. Once assigned a value, these variables cannot be reassigned to another value. They are effectively read-only and can be accessed throughout the class. Constants are often named using uppercase letters with underscores separating words, following the convention to distinguish them from regular variables.

#### Benefits of Constants:

1. **Readability:** Constants improve code readability by providing meaningful names for fixed values, making it clear what the values represent.
2. **Maintainability:** Constants make it easier to update and maintain code. If a constant value needs to change, you only need to update it in one place (where it's declared) rather than searching for all occurrences throughout the code.
3. **Prevents Modification:** Constants prevent accidental or intentional modification of important values, ensuring that critical parameters remain constant during the program's execution.

#### Constants in Interfaces:

In Java, interfaces can also contain constants. All variables declared in an interface are implicitly `public`, `static`, and `final`. Therefore, any variable defined in an interface is a constant and must be initialized with a value.

**Interface with Constants:**

```java
public interface Constants {
    double PI = 3.14159;
    int MAX_SIZE = 100;
}
```

In the above example, `PI` and `MAX_SIZE` are constants defined in the `Constants` interface. Implementing classes can use these constants without the need to redeclare them.

Using constants in Java helps improve code quality and maintainability by providing a clear and standardized way to define and use fixed values.
