A constant is a quantity that is unchanged from the beginning of the program to the end. In Java programming, use the keyword "final" to declare a constant, such as the following program code.
The x here is a constant, but it is a constant within a method, or it can be called a member constant (the name given to it by the author)
public class var{
public static void Main (string[] args) {
var m=new var ();
final int x=20;
SYSTEM.OUT.PRINTLN ("Constant x=" +x);
}
}
The operating result is:
Constant x=20
If you want to declare a class constant, you need to use a combination of the keyword "static" and "final", such as the following example.
The x here is a class constant, so no matter which object is referenced, its value remains the same.
public class var{
static final int x=20;
public static void Main (string[] args) {
SYSTEM.OUT.PRINTLN ("Print data x=" +x);
}
}
The operating result is:
Print Data x=20
As can be seen from the above example, if the constant is a class constant, then you can refer to the constant without having to construct the object again. The previous example declares that the constant is a general constant, not a class constant, so be sure to construct the object, referencing it by object, so remember the difference between a class constant and a general constant.
Declaration and use of 4.Java constants