Declaration and use of 4.Java constants

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.