How to Create Constants In Java?


A quick practical guide and best guidelines for defining constants in java. Creating constants can be done using final and static keywords.

1. Overview

In this core java tutorial series, You'll learn today how to create a constant in java and what is the best way to create a java constant.
A constant is a variable whose value cannot be changed once it has been assigned. In fact, java does not have any built-in keyword to create constantly. But, Java provides a set of modifiers final and static. These can be applied to the variables to make them effectively constant.

Constants can make your program more easily read and understood by others. In addition, a constant is cached by the JVM as well as your application, so using a constant can improve performance.

First, let us go through on final and static keywords in java.

                                     How to Create Constants In Java?

2. Static Modifier Keyword

Static is a keyword and can be used on instance varaible. Once a variable is declared as static, then it allows accessing the variables without creating the instance for that class. A static member is associated with class and not with the objects. So that means even if multiple instances have been created, all instances share the same memory and value. If any of the instance changes the value of static varaible then all other instances will get the newly updated value.

See the below example program on static:

class Calculation {

    public static double PI = 3.14;

    public Calculation() {

Class Calculation has a static variable PI which value is assigned with 3.14. Now accessing the PI with the class name and printing the value.

package com.javaprogramto.engineering.programs.constants;

public class StaticModiferExample {

    public static void main(String[] args) {

        double piValue = Calculation.PI;
        System.out.println("PI value : " + piValue);


PI value : 3.14

Create multiple instances for Calculation class and modify the PI value with object2. Let us see what is the value in object 1.

        // created first object for Calculation class
        Calculation object1 = new Calculation();
        // created second object for Calculation class
        Calculation object2 = new Calculation();
        // Updating PI vlaue for object2.
        object2.PI = 9;
        // printing the value from object2.
        System.out.println("object 1 PI value : "+object1.PI);


object 1 PI value : 9.0

This is the example to prove that a static variable is shared by all objects created for the class. Because of this, we are seeing a new value when using object1.PI.

3. Final Modifier Keyword

final is a built-in keyword in java to make the variable value not to change. Once a variable is declared as final then its values cannot be changed and reassigned with a new value.

final keyword example:

The same class was used in the static example but dut declared the PI only with final.

class Calculation {

    public final double PI = 3.14;

    public Calculation() {

Creating multiple objects.

public class FInalModiferExample {

    public static void main(String[] args) {

        Calculation object1 = new Calculation();
        Calculation object2 = new Calculation();
        Calculation object3 = new Calculation();

        System.out.println("object1 PI value : " + object1.PI);
        System.out.println("object2 PI value : " + object2.PI);
        System.out.println("object3 PI value : " + object3.PI);



object1 PI value : 3.14
object2 PI value : 3.14
object3 PI value : 3.14

All are pointing the same value and value can not be changed. If value is reassigned then it produces a compile-time error.

object2.PI = 90;


Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The final field Calculation.PI cannot be assigned

    at com.javaprogramto.engineering.programs.constants.FInalModiferExample.main(FInalModiferExample.java:15)

Here the problem is memory is not reused and creates a separate memory for a PI final variable when each object is created. So, if 1000 objects are created for Calculation class then lots of memory wasted.

Take a look at the final class references.

4. Defining a Java Constant Variable

in previous sections, we have seen how static and final works. What are the problems when using them individually? The following are the guidelines and best practices to create constants in java.

A) Make all letters in constant variable Captial Letters.
B) Should declare as static and final. Both are required.
C) Should be a public variable. So that constat can be accessed from outside classes wherever needed.
D) Use only primitive types as constant types.
E) Do not use objects created with a new keyword. Because the only reference is treated as constant and values inside the object can be modified using its setters methods.
F) If you using objects as a constant then all of its references should be Immutable objects.

Java Constant Example:

Below are valid. Because all are primitives and String. The string is immutable so it will not give data inconsistency issues.

    public static final double PI = 3.14;
    public static final String STATUS_COMPLETED = "COMPLETED";
    public static final String STATUS_IN_PROGRESS = "IN_PROGRESS";
    public static final int RETRY_COUNT = 10;


public statis final List  STATUSES = new ArrayList();

Here, the list is holding Status objects and those values can be changed as below. Becuase Status is a mutable object.

STATUSES.get(3).status = "UNKNOWN"; 

Please make sure, not adding the mutable objects as part of constants.

5. Conclusion

In this tutorial, We've seen how to create efficient constants in java. What are the best guidelines and practices to make constants? Shown examples on valid and invalid constants.



About Us

Author: Venkatesh - I love to learn and share the technical stuff.

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
JavaProgramTo.com: How to Create Constants In Java?
How to Create Constants In Java?
A quick practical guide and best guidelines for defining constants in java. Creating constants can be done using final and static keywords.
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content