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.
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_STUDENTS
with a value of100
.
There are several cases where using constants can be helpful. They are as follows:
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.");}}
NUM_STUDENTS
using the final
keyword inside the main
method. println
command displays the value of the constant at the output.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.");}}
NUM_STUDENTS
using the final
keyword inside the Main
class. We also use the static
keyword that makes the constant available for all instances of the class. println
command is displays the value of the constant at the output.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.");}}
NUM_STUDENTS
inside the IClassConstants
interface. In the case of an interface, public
and static
keywords are redundant but it is good programming practice to use them.println
command displays the value of the constant at the output.