In this tutorial, we will learn about the final keyword in Java. The main motive of the final keyword is to restrict the user and final keyword can be used to create three kinds of restriction. These are:
Page Contents
Final keyword in Java with variable:
The final keyword is to make the variable final(constant). Once you declared a variable with the final keyword you can not change the value of this final variable throughout the program.
Example Program:
class Math{
final static double pi=3.14;
public static void main(String args[]){
System.out.println("Value of Pi is "+pi);
//pi=2.5; if you will try to assign value compiler will show an error
}
}
Final keyword in Java with Method:
When we make a method final in class it means we cannot override this method in child class.
Example Program:
class Math{
final static double pi=3.14;
final public void squareRoot(int num){
System.out.println("SQ ans is "+(num*num));
}
}
public class Calculator extends Math{
//if we try to override this function it will show an error
/*public void squareRoot(int num){
System.out.println("SQ ans is "+(num*num));
}*/
public static void main(String args[]){
Calculator cal=new Calculator();
cal.squareRoot(5);
}
}
Final keyword with Class:
When we use final keyword with a class, it means we can not inherit this class in any other class. The following code will show an error.
final class Math{
final static double pi=3.14;
public void squareRoot(int num){
System.out.println("SQ ans is "+(num*num));
}
}
public class Calculator extends Math{
public static void main(String args[]){
Calculator cal=new Calculator();
cal.squareRoot(5);
}
}
Have you ever tried to inherit String class in your class. You can not inherit String class because it is a final class. Click here to check.
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
