×

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

Leap Year Program in Java

Leap Year Program in Java: A leap year is a calendar year that have an extra day i.e. 366 days instead of 365 days is called leap year. In other...

2 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Java finalize()

Java finalize() In Java, the Object class is the root class that is inherited by all the Java classes. The class provides the finalize() method that is called just before the...

4 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.