Java/J2EE and SOA (324 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (323 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is a Constant in Java and how to declare it?

Published on Sep 27,2019 201 Views
11 / 72 Blog from Java Core Concepts

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

‘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.

Let us begin!

What is Constant in Java?

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 static modifier causes the variable to be available without an instance of it’s defining class being loaded
  • The final modifier makes the variable unchangeable

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:

image1- Constant in Java- Edureka 

Now let us see why Constants.

Why constants?

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.

Static and Final Modifiers

  • The static modifier is mainly used for memory management.
  • It also allows the variable to be available without loading any instance of the class in which it is defined.
  • The final modifier means that the value of a variable cannot change. Once the value is assigned to a variable, a different value cannot be reassigned to the same variable.

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:

Image2- Constant in Java- Edureka

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: 

Image3- Constant in Java- Edureka

Moving on with Potential Problems With Constant Variables

 

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.

Constants using Enumeration

  • An enumeration is a list of named constants.
  • It is similar to final variables.
  • The enumeration in java is a data type that contains a fixed set of constants.
  • An enumeration defines a class type in Java. By making enumerations into classes, it can have constructors, methods, and instance variables.
  • An enumeration is created using the enum keyword.

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:

  • public static enum-type[ ].values( )
  • public static enum-type.valueOf(String str)

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: 

Output - Edureka

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 Training 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.

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.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.