$show=/label

How to Create A Java Constants Variable (Static/Final modifiers keywords?)

SHARE:

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 constant in java and what is the best way to create java constant.
A constant is a variable whose value cannot be changed once it has been assigned. In fact, java does not have any builtin keyword to create constant. But, Java provides a set of modifiers final and static. These can be applied on 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 A Java Constants Variable (Static/Final modifiers keywords?)


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);
    }
}

Output:

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);

Output:

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 the new value when using object1.PI.

3. Final Modifier Keyword


final is a builtin keyword in java to make the variable value not to change. Once a variable is declared as final then it's values cannot be changed and reassigned with a new value.

final keyword example:


The same class 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);

    }
}

Output:

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;

Error:


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;

Invalid:

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.

COMMENTS

BLOGGER

About Us

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

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,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,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How to Create A Java Constants Variable (Static/Final modifiers keywords?)
How to Create A Java Constants Variable (Static/Final modifiers keywords?)
A quick practical guide and best guidelines for defining constants in java. Creating constants can be done using final and static keywords.
https://1.bp.blogspot.com/-wPTHZFdxfVs/XfSmWZxakYI/AAAAAAAACC4/j7R6H6WADkQgG5bYOqGhmwLNOuYzoCMdACLcBGAsYHQ/s640/How%2Bto%2BCreate%2BA%2BJava%2BConstants%2BVariable%2B%2528Static%253AFinal%2Bmodifiers%2Bkeywords%253F%2529.png
https://1.bp.blogspot.com/-wPTHZFdxfVs/XfSmWZxakYI/AAAAAAAACC4/j7R6H6WADkQgG5bYOqGhmwLNOuYzoCMdACLcBGAsYHQ/s72-c/How%2Bto%2BCreate%2BA%2BJava%2BConstants%2BVariable%2B%2528Static%253AFinal%2Bmodifiers%2Bkeywords%253F%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/12/java-create-use-constants.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/12/java-create-use-constants.html
true
3124782013468838591
UTF-8
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