DEV Community

Cover image for Named Constants
Paul Ngugi
Paul Ngugi

Posted on

Named Constants

A named constant is an identifier that represents a permanent value. The value of a variable may change during the execution of a program, but a named constant, or simply constant, represents permanent data that never changes. For example, pie of a circle is a constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for pie. Here is the syntax for declaring a constant:



final datatype CONSTANTNAME = value;



Enter fullscreen mode Exit fullscreen mode

A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant.

Image description

There are three benefits of using constants:

  • you don’t have to repeatedly type the same value if it is used multiple times;
  • if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single location in the source code;
  • a descriptive name for a constant makes the program easy to read.

Top comments (0)