×

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

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 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.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java import packages

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Sales Tax Problem in Java

To calculate the sales tax on a purchase in Java, you will need to know the following information: The cost of the item being purchased The sales tax rate You can then use...

4 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

String Matches in Java

Firstly we have to know something about String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java...

3 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Heap Implementation in Java

The root node or parent node of a Java heap is compared to its left and right offspring, and the children are then ordered in line with the comparison.Assuming that...

9 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.