How to declare constants in Java
Introduction
In Java, a constant is a variable whose value cannot be changed once it's assigned.
Constants are often used to represent values that will not change, such as the number of students in a class. They can also be used to make the code more readable by giving names to values that would otherwise be hard to remember.
A constant can be declared within a method, class, or interface. When declaring constants, it's good practice to use all uppercase letters for the constant name. This makes it easier to identify constants in code.
Syntax
To declare a constant in a class, we use the final keyword:
public final int NUM_STUDENTS = 100;
To declare a constant in an interface, use the static and final keywords:
public static final int NUM_STUDENTS = 100;
Note: The statements above declare a constant named
NUM_STUDENTSwith a value of100.
When should we use constants?
There are several cases where using constants can be helpful. They are as follows:
- To make code more readable by giving names to values
- To prevent a variable from being changed accidentally
- To enforce the immutability of an object
Example 1
Here is a Java program demonstrating the use of constant within a method:
public class Main {public static void main(String[] args) {final int NUM_STUDENTS = 100;System.out.println("There are " + NUM_STUDENTS + " students in this class.");}}
Explanation
- Line 4: We declare a constant named
NUM_STUDENTSusing thefinalkeyword inside themainmethod. - Line 5: The
printlncommand displays the value of the constant at the output.
Example 2
Here is a Java program that demonstrates the use of a constant within a class:
public class Main {public static final int NUM_STUDENTS = 100;public static void main(String[] args) {System.out.println("There are " + NUM_STUDENTS + " students in this class.");}}
Explanation
- Line 2: We declare a constant named as
NUM_STUDENTSusing thefinalkeyword inside theMainclass. We also use thestatickeyword that makes the constant available for all instances of the class. - Line 4: The
printlncommand is displays the value of the constant at the output.
Example 3
Here is a Java program that demonstrates the use of a constant within an interface:
interface IClassConstants {int NUM_STUDENTS = 100;}public class Main implements IClassConstants{public static void main(String[] args) {System.out.println("There are " + NUM_STUDENTS + " students in this class.");}}
Explanation
- Line 2: We declare a constant named
NUM_STUDENTSinside theIClassConstantsinterface. In the case of an interface,publicandstatickeywords are redundant but it is good programming practice to use them. - Line 7: The
printlncommand displays the value of the constant at the output.