How to define constants in Java

In Java, the final keyword can be used to define constants, whose values cannot be changed after being defined.

Constants can be defined anywhere within a class, but they are typically defined as static final class member variables for global access.

Here is an example of defining constants:

public class MyClass {
    public static final int MAX_VALUE = 100; // 定义一个整数常量

    public static final String DEFAULT_NAME = "John"; // 定义一个字符串常量

    public static final double PI = 3.14; // 定义一个浮点数常量

    // ...
}

Please note that constants are typically named with all capital letters, and multiple words are separated by underscores. This is a common naming convention that can improve code readability.

bannerAds