Java Constants: Assign Variable to `final` Value

In Java, constants are defined using the keyword final and cannot be changed once assigned. To assign a variable to a constant, you can use the final keyword in the variable declaration to define a constant and then assign the variable’s value to this constant. For example:

public class Main {
    public static void main(String[] args) {
        final int num = 10;
        int x = 5;
        // 将变量x的值赋给常量num
        //num = x; // 这里会报错,因为常量num的值无法更改
        System.out.println("num: " + num);
    }
}

In the example above, the value of variable x is assigned to the constant num. However, since num is declared as a constant, it cannot be reassigned, otherwise it will result in a compilation error.

bannerAds