Java Constant
-
Declare and Use Constant Using
private
,static
, andfinal
Keywords in Java -
Declare and Using Constant Using
public
,static
, andfinal
Keywords in Java
This article will introduce the topic of the Java constant. A constant value is a value that cannot be changed once it is assigned. Java has the word const
reserved, but it does not provide any functionality to implement and use constants. But there are other ways that we can use to use constants, like using the keywords static
and final
that we are going to see in the following examples.
Declare and Use Constant Using private
, static
, and final
Keywords in Java
In the first example, we use the two keywords - static
and final
with the private
access modifier. We have a class, and inside it is a constant MIN_VOTING_AGE
is declared and initialized.
We ask the user to enter his/her age to check the eligibility for voting. Once the user inputs age, we check if it is greater than the constant MIN_VOTING_AGE
. Then it shows the appropriate output according to the condition.
The private
keyword ensures that the constant is not accessible outside the class.
import java.util.Scanner;
public class JavaConstants {
private static final int MIN_VOTING_AGE = 18;
public static void main(String[] args) {
System.out.println("Enter your age and check if you are old enough to vote: ");
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if (age > MIN_VOTING_AGE) {
System.out.println("Congrats, You are eligible to vote");
} else {
System.out.println("You are not eligible to vote yet.");
}
}
}
Output:
Enter your age and check if you are old enough to vote:
12
You are not eligible to vote yet.
Declare and Using Constant Using public
, static
, and final
Keywords in Java
This example uses static
and final
keywords but with the public
access modifier. We create a class, AnotherClass
, that has the constant MIN_VOTING_AGE
defined using public static final int
. As the constant is public
, we can use the constant in the JavaConstants
class to access the constant, and we call it using AnotherClass.MIN_VOTING_AGE
as it is static.
import java.util.Scanner;
public class JavaConstants {
public static void main(String[] args) {
System.out.println("Enter your age and check if you are old enough to vote: ");
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if (age > AnotherClass.MIN_VOTING_AGE) {
System.out.println("Congrats, You are eligible to vote");
} else {
System.out.println("You are not eligible to vote yet.");
}
}
}
class AnotherClass {
public static final int MIN_VOTING_AGE = 18;
}
Output:
Enter your age and check if you old enough to vote:
23
Congrats, You are eligible to vote
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn