Pages

Friday, December 17, 2021

How to Create Constants In Java?

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

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

    }
}

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.


No comments:

Post a Comment

Please do not add any spam links in the comments section.