The final keyword in Java has various uses. In this article, we are going to look at only one of its uses. Other two uses of the final keyword are related to inheritance. So final keyword will be again revisited in the inheritance concept.
Primary use of the final keyword is to declare constants in Java programs. A constant is like a variable but, whose value cannot be changed once initialized. Syntax for declaring a constant using final keyword is shown below:
final data-type identifier = value;
You should remember that a constant should be initialized at the time of declaration itself. Once a constant has been initialized, it cannot be modified later. For example you can declare a PI constant as shown below:
final float PI = 3.14;
Java’s convention for constant names is that they should be written in uppercase. Below code segment demonstrates the use of constants (created using final keyword) in a Java program:
class Circle
{
float radius;
final float PI = 3.14;
void displayArea()
{
float area;
radius = 2.3;
area = PI * radius * radius;
System.out.println("Area of the circle is: "+area);
}
}
There are two more uses of final keyword which will be discussed in inheritance section.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply