Named Constants
Paul Ngugi
Posted on April 24, 2024
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;
A constant must be declared and initialized in the same statement. The word final is a Java keyword for declaring a constant.
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.
💖 💪 🙅 🚩
Paul Ngugi
Posted on April 24, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.