Full Stack Web Development Internship Program
- 5k Enrolled Learners
- Weekend/Weekday
- Live Class
‘Constant’ word in the English language basically refers to ‘a situation that does not change‘. It is one of the fundamental concepts of programming and it does not have any special prerequisites or concepts to be known before learning it, other than basic programming skill. Here are the concepts on which we’ll work in this article.
Constants in Java are used when a ‘static‘ value or a permanent value for a variable has to be implemented. Java doesn’t directly support constants. To make any variable a constant, we must use ‘static’ and ‘final’ modifiers in the following manner:
Syntax to assign a constant value in java:
static final datatype identifier_name = constant;
The reason that we have to use both static and final modifiers is that if we declare a variable ‘var’ only as static, all the objects of the same class will be able to access this ‘var’ and change its values. When we declare a variable only as final, then multiple instances of the same constant value will be created for every different object and that isn’t efficient/desirable. When we use both static and final, then, the ‘var’ remains static and can be initialized only once, thereby making it a proper constant which has a common memory location for all objects of it’s containing class.
Example for a constant declaration: static final int MIN_AGE = 18; Let’s say we need to determine who all are eligible to get a permanent driving license in a group of people. We already know that the minimum age requirement for a permanent driving license is 18. So instead of asking the user to enter the minimum age for comparison, we declare the ‘MIN_AGE’ identifier as a constant integer with value 18.
import java.util.*; public class DrivingLicense{ public static void main(String [] args){ Scanner sc = new Scanner(System.in); static final int MIN_AGE = 18; //Minimum age requirement int[] list = new int[5]; System.out.println("Enter the age of people:"); for(int i=0;i<5;i++){ list[i] = sc.nextInt(); } System.out.println("Result for eligibility:"); for(int i=0;i<5;i++) { if(list[i] >= MIN_AGE) System.out.println(i + " is Eligible"); else System.out.println(i + " is Not Eligible"); } } }
Output:
Constants make your program more easy to read and understand when read by others.
Using a constant also improves performance, as constants are cached by both the JVM and your application.
Let us check the Static and Final Modifiers.
By using the final modifier, Primitive data types like int, float, char, byte, long, short, double, Boolean all can be made immutable/unchangeable.
Together, as we understood earlier, these modifiers create a constant variable.
General Syntax: public static final int MAX_VALUE=1000; It is a convention to capitalize the name of a variable that we want to declare as a constant. If we keep the access specifier for a constant variable as private, then its values cannot be changed in that class but if we keep the access specifier as public for a constant variable, then its values can be changed anywhere in the program.
Example 1:
public class ExampleSetOne { private static final int MAX=10; public static void main(String[] args){ System.out.println("Final variable MAX="+MAX); ESO e = new ESO(); e.printMAX(); } } class ESO{ private static final int MAX=20; void printMAX(){ System.out.print("Final variable MAX changed="+MAX); } }
Output:
Example 2:
public class ExampleSetTwo { public static final int MAX = 10; public static void main(String[] args) { printMAX(); MAX = 20; printMAX(); } void printMAX() { System.out.print("Final variable MAX changed=" + MAX); } }
Output:
Moving on with Potential Problems With Constant Variables
The working of the final keyword in Java is that the variable’s pointer to the value is made unchangeable. That means it’s the pointer that is unable to change the location to which it’s pointing.
There’s no guarantee that the object being referenced will stay the same but only that the variable being finalized will always hold a reference to the same object.
If the referenced object is mutable (i.e. has fields that can be changed), then the constant variable may contain a value other than what was originally assigned.
Now let us look into the Constants using Enumeration.
Example:
enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland; } class EnumDemo { public static void main(String args[]) { Apple ap; ap = Apple.RedDel; System.out.println("Value of ap: " + ap);// Value of ap: RedDel ap = Apple.GoldenDel; if(ap == Apple.GoldenDel) System.out.println("ap contains GoldenDel.n"); // ap contains GoldenDel. switch(ap){ case Jonathan: System.out.println("Jonathan is red."); break; case GoldenDel: System.out.println("Golden Delicious is yellow."); // Golden Delicious is yellow break; case RedDel: System.out.println("Red Delicious is red."); break; case Winesap: System.out.println("Winesap is red."); break; case Cortland: System.out.println("Cortland is red."); break; } } }
In this example, we used an enumeration as enum Apple {Jonathan, GoldenDel, RedDel, Winesap, Cortland}. The identifiers Jonathan, GoldenDel, RedDel, Winesap and Cortland are called enumeration constants. Each is implicitly declared as a public static final member of Apple. Enumeration variable can be created like another primitive variable. It does not use ‘new’ for creating an object.
Example: Apple ap;
‘ap’ is of type Apple, the only values that it can be assigned (or can contain) are those defined by the enumeration.
For example, this assigns ap = Apple.RedDel;
All enumerations have two predefined methods: values( ) and valueOf( ).
The syntax of these built-in methods are:
The values( ) method gives an array that consists of a list of the enumeration constants.
The valueOf( ) method gives the enumeration constant whose value is in correspondence to the string passed in str.
Example:
enum Season { WINTER, SPRING, SUMMER, FALL; } class EnumExample { public static void main(String[] args) { for (Season s : Season.values()) System.out.println(s);//will display all the enum constants of Season Season s = Season.valueOf("WINTER"); System.out.println("S contains " + s);//output: S contains WINTER } }
Output:
In the example shown above, we used the two in-built methods of Enumeration. To know more about enumeration please click here.
Summary
In a nutshell, we learned that constants are a fundamental concept of programming and they are used to implement fixed conditions or data. They are implemented in Java using variable modifiers such as ‘static’ and ‘final’, they can also be implemented as enumerations. With this we come to the end of the article, hope it was helpful.
Also, you can check out the Java Online Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a successful Java Developer, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.
Got a question for us? Please mention it in the comments section of this “Constant in Java” blog and we will get back to you as soon as possible or you can also join our Java Training in UAE.
Course Name | Date | |
---|---|---|
Java Certification Training Course | Class Starts on 28th January,2023 28th January SAT&SUN (Weekend Batch) | View Details |
Java Certification Training Course | Class Starts on 25th February,2023 25th February SAT&SUN (Weekend Batch) | View Details |
edureka.co