• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Final Keyword in Java | Java Tutorial

August 25, 2015 by javainterviewpoint Leave a Comment

As a programmer it is very much essential to know the uses of final keyword in Java. final keyword can be used along with variables, methods and classes. In this article we will be looking into the following topics.

1) final variable
2) final method
3) final class

1. Java final variable

A final variable is a variable whose value cannot be changed at anytime once assigned, it remains as a constant forever. Lets look into the below code

Example of final variable

public class Travel 
{
    final int SPEED=60;
    void increaseSpeed(){  
       SPEED=70;
    }  
    public static void main(String args[])
    {  
       Travel t=new  Travel();  
       t.increaseSpeed();  
    }  
}

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final field Travel.SPEED cannot be assigned

	at com.javainterviewpoint.Travel.increaseSpeed(Travel.java:7)
	at com.javainterviewpoint.Travel.main(Travel.java:12)

The above code will give you Compile time error, as we are tying to change the value of a final variable ‘SPEED’.

Can we have a uninitialized  final variable ?

No, we cannot have a final variable which is not initialized.

package com.javainterviewpoint;

public class Travel 
{
    final int SPEED;
    public static void main(String args[])
    {  
       Travel t=new  Travel();  
       System.out.println("Travelling Speed is :"+t.SPEED);
    }  
}

Output :

We will get a error like “The blank final field SPEED may not have been initialized”. All the final variable has to be initialized at the very beginning or you can initialize through a constructor(blank final variable) which we will see in the later part.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The blank final field SPEED may not have been initialized

	at com.javainterviewpoint.Travel.(Travel.java:3)
	at com.javainterviewpoint.Travel.main(Travel.java:8)

What is a blank final variable ?

A final variable which is not initialized at the time of declaration is known as blank final variable. We must initialize a blank final variable in the constructor else it will throw compilation error. Lets now change the above to initialize the “SPEED” variable through a constructor.

package com.javainterviewpoint;

public class Travel 
{
    final int SPEED;
    Travel()
    {
        SPEED = 60;
    }
    public static void main(String args[])
    {  
       Travel t=new  Travel();  
       System.out.println("Travelling Speed is :"+t.SPEED);
    }  
}

Output :

Travelling Speed is :60

What is the use of a blank final variable ?

Lets say we have a class Employee, consisting a field called SOCIAL_SECURITY_NUMBER. Once the employee is registered the SOCIAL_SECURITY_NUMBER cannot be changed and we cannot initialize the SOCIAL_SECURITY_NUMBER well in advance as it differs for each employee. In such cases we can use the blank final variable and initialize the final variable like below.

package com.javainterviewpoint;

public class Employee
{
    public final int SOCIAL_SECURITY_NUMBER;
    Employee(int ssn)
    {
        SOCIAL_SECURITY_NUMBER = ssn;
    }
    public static void main(String args[])
    {
        Employee e1 = new Employee(1234);
        System.out.println("Social Security Number of Emploee e1 : "+e1.SOCIAL_SECURITY_NUMBER);
        Employee e2 = new Employee(5678);
        System.out.println("Social Security Number of Emploee e2 : "+e2.SOCIAL_SECURITY_NUMBER);
    }
}

Output :

Social Security Number of Emploee e1 : 1234
Social Security Number of Emploee e2 : 5678

what is Static blank final variable?

A static final variable is a variable which is also not initialized at the time of declaration. It can be initialized only in static block.

package com.javainterviewpoint;

public class Employee
{
    public static final int SOCIAL_SECURITY_NUMBER;
    static
    {
        SOCIAL_SECURITY_NUMBER = 1234;
    }
    public static void main(String args[])
    {
        Employee e1 = new Employee();
        System.out.println("Social Security Number of Emploee e1 : "+e1.SOCIAL_SECURITY_NUMBER);
    }
}

Output :

Social Security Number of Emploee e1 : 1234

2. Java final method

When you declare a method as final, then it is called as final method. A final method cannot be overridden.

package com.javainterviewpoint;

class Parent
{
    public final void disp()
    {
        System.out.println("disp() method of parent class");
    }
}
public class Child extends Parent
{
    public void disp()
    {
        System.out.println("disp() method of child class");
    }
    public static void main(String args[])
    {
        Child c = new Child();
        c.disp();
    }
}

Output : We will get the below error as we are overriding the disp() method of the Parent class.

Exception in thread "main" java.lang.VerifyError: class com.javainterviewpoint.Child overrides final method disp.()V
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at java.net.URLClassLoader.defineClass(Unknown Source)
	at java.net.URLClassLoader.access$100(Unknown Source)
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.net.URLClassLoader$1.run(Unknown Source)

Can a final method be inherited ?

Yes, the final method can be inherited but cannot be overridden.

package com.javainterviewpoint;

class Parent
{
    public final void disp()
    {
        System.out.println("disp() method of parent class");
    }
}
public class Child extends Parent
{
    public static void main(String args[])
    {
        Child c = new Child();
        c.disp();
    }
}

Output :
The above example clearly shows that the disp() method of the Parent class is inherited to the Child class.

disp() method of parent class

3. Java final class

A final class cannot be extended(cannot be subclassed), lets take a look into the below example

package com.javainterviewpoint;

final class Parent
{
}
public class Child extends Parent
{
    public static void main(String args[])
    {
        Child c = new Child();
    }
}

Output :
We will get the compile time error like “The type Child cannot subclass the final class Parent”

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

	at com.javainterviewpoint.Child.main(Child.java:8)

Other interesting articles which you may like …

  • JVM Architecture – Understanding JVM Internals
  • Object and Object Class in Java
  • Difference between JDK, JRE and JVM
  • Components of Java Development Kit (JDK)
  • What is a Class in Java with Example
  • How to open .class file in Java
  • How to Set Classpath for Java in Windows
  • ClassNotFoundException Vs NoClassDefFoundError
  • How HashMap works in Java
  • How to make a class Immutable in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of polymorphism in Java
  • Types of Inheritance in Java
  • Java does not supports Multiple Inheritance Diamond Problem?
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword

Filed Under: Core Java, Java, OOPs Tagged With: Final, Final Class, Final Keyword, Final Method, Final variable, Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2022 · Java Interview Point - All Rights Are Reserved ·