Named Constants

paulike

Paul Ngugi

Posted on April 24, 2024

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.
💖 💪 🙅 🚩
paulike
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.

Related

Augmented Assignment Operators
java Augmented Assignment Operators

April 24, 2024

Numeric Literals
java Numeric Literals

April 24, 2024

Named Constants
java Named Constants

April 24, 2024

Programming Errors
java Programming Errors

April 22, 2024