×

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how to define them in this article.

Definition

A constant is a variable that, once assigned, cannot be altered. The constants are not directly supported by Java. Both non-access modifiers static as well as final can be used as a substitute when defining constants in Java.

Declaration of Constant in Java

In Java, the static and final modifiers are used to define any value as a constant. They are also referred to as non-access modifiers. The identifying name has to be in upper case letters in accordance with the Java naming convention.

Final and Static Modifiers

Utilizing the static modifier is done so that memory can be managed.

The variable can also be used without having to load any instances of the class in which it has been declared.

The final modifier indicates that the variable's value cannot be altered. Additionally, it declares the primitive data type unchangeable or immutable. The last modifier fixes the variable, making it accessible without the requirement to import an instance of its containing class due to the static modifier.

All instances of the class (within which the constant is declared) will be capable of accessing the variable and modify its value if it is declared as static. We leverage the final modifier together with a static modifier to solve this issue.

It is inappropriate to establish numerous instances with the same constant value for each particular object once the variable is identified as final.

The variable remains unchanged and only needs to be instantiated once when the static and final modifiers are used next to each other. Hence, we apply both the static and final modifiers to specify a variable to be a constant. All instances of its enclosing class are stored in the same shared memory address.

The purpose of Constants

Constants are used in programming to keep systems simple and comprehensible so that they can be widely interpreted by others. Even though a constant variable is memorized by both the JVM and the software, it also has an effect on performance.

Declaration Techniques

  • Capitalize the title of the identifier that you intend to define as constant.
  • If the private access-specifier is used just before constant name, the constant's value cannot be altered in that specific class.
  • The constant's value can be modified in the program if the public access-specifier is used before its name.

Now, lets acknowledge ourselves the declaration of constants and usage of constants in specific circumstances. Go through the following programs to understand

In the following example, we have declared constant X as private. Inside the Demo() class, we have assigned  in the constant X. After that, we have invoked the displayX() method.

File Name: Demo1.java

public class Demo1
{  
private static final double X=75;  
public static void main(String[] args)  
{  
System.out.println("Previous value of Dollar in Indian currency: "+X);  
Demo d = new Demo();  
d.displayX();  
}  
}  
class Demo
{  
private static final double X=79;  
void displayX()  
{  
System.out.println("Current Value of Dollar in Indian currency: "+X);  
}  
}

Output

Previous value of Dollar in Indian currency: 75.0
Current Value of Dollar in Indian currency: 79.0

In the following example, we have declared constant L as public. Inside the display() method, we have assigned  in the constant L. After that, we have invoked the display() method.

File name: Demo2.java

public class Demo2 
{  
//declaring L as constant   
public static final double L= 10;  
public static void main(String[] args)   
{  
display();    
L = 20;  
display();  
}  
void dsiplay()   
{  
System.out.print("The value of L cannot be changed " + L);  
}  
}  

Output

Demo2.java:8: error: cannot assign a value to final variable X
L = 20;

A unique data type called an Enum permits a variable to be a collection of specified constants. A previously defined parameter for the variable must match the variable in question. Popular uses could include days of every week or compass headings.

File name: Enum2.java

public class Enum2
{    
//defining the enum   
public enum Languages {C,Python,Java,HTML,Javascript}    
public static void main(String[] args)   
{    
//traversing the enum    
for (Languages l : Languages.values())    
System.out.println(l);    
}  
}    

Output

C
Python
Java
HTML
Javascript

Related Topics

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java String indexOf() method

Java String indexOf() method returns index of a given character or substring present in a String. Methods Description int indexOf(int ch)     It returns index position for the given char value.int indexOf(int ch,...

2 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Array Programs in Java

Array Programs in Java: An array is a data structure that stores similar elements in a contiguous memory location. In Java, an array is an object that stores the same...

7 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java.net.ConnectionException

java.net.ConnectException: Connection rejected: the interface is the most continuous sort of happening, organizing special cases in Java at whatever point the product is in client-server engineering and attempting to make...

3 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.