Understanding Final, Finally, and Finalize in Java

Alexander Obregon
3 min readApr 6, 2023

--

Image Source

Introduction

Java provides us with three important keywords — ‘final’, ‘finally’, and ‘finalize’. Although they may appear similar, they serve very different purposes in the Java programming language. In this article, we will delve into each keyword and explain their differences, complete with code examples to help you better understand their functionalities.

Final

The keyword final in Java is highly versatile, serving to declare entities in your code that cannot be later modified. It's applicable to variables, methods, and classes, each of which serves distinct purposes.

Final Variables

When you declare a variable as final, it must be initialized only once. Once a final variable has been assigned a value, attempting to modify it will result in a compile-time error. This immutable property makes final variables akin to constants.

public class FinalVariableExample {
public static void main(String[] args) {
final int MY_CONSTANT = 10;
// Attempting to reassign a value to MY_CONSTANT will result in a compile-time error:
// MY_CONSTANT = 20;
}
}

Final Methods

Final methods are methods that cannot be overridden in any subclass. This is particularly useful when you need to maintain a consistent implementation of a method across various subclasses in the class hierarchy, thus avoiding unintended behaviors or security breaches.

public class Animal {
public final void makeSound() {
System.out.println("The animal makes a sound");
}
}

public class Dog extends Animal {
// This will trigger a compile-time error:
// @Override
// public void makeSound() {
// System.out.println("The dog barks");
// }
}

Final Classes

A final class is one that cannot be subclassed. This restriction is typically employed to maintain the immutability of the class or to provide a guarantee that certain behavior is preserved without alteration through inheritance. Final classes are often used in conjunction with final variables to create fully immutable objects which are thread-safe by design.

public final class ImmutableClass {
private final int value;

public ImmutableClass(int value) {
this.value = value;
}

public int getValue() {
return value;
}
}

// This will result in a compile-time error:
// public class ExtendedClass extends ImmutableClass { }

Finally

The finally keyword is integral to Java's exception handling model. It is used to create a block of code that follows a try-catch structure, ensuring that it is executed regardless of whether an exception was thrown or caught in the try-catch blocks. This feature is especially useful for cleanup activities, such as closing file streams or database connections, ensuring that resources are properly released regardless of whether the operation succeeded or failed.

public class FinallyExample {
public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
} finally {
System.out.println("This block is always executed");
}
}
}

Finalize

The finalize() method in Java objects is called by the garbage collector when it determines that there are no more references to the object. Overriding the finalize method allows the object to complete cleanup activities before it is irrevocably discarded. However, its usage is generally discouraged due to the unpredictable nature of garbage collection timing and the potential for errors and performance issues. Instead, Java's try-with-resources and other explicit cleanup mechanisms are recommended.

public class FinalizeExample {
@Override
protected void finalize() throws Throwable {
try {
System.out.println("Finalize method called");
} finally {
super.finalize();
}
}

public static void main(String[] args) {
FinalizeExample obj = new FinalizeExample();
obj = null;
System.gc(); // Suggesting the JVM to call garbage collector
}
}

Conclusion

The ‘final’ keyword is used to create constants or non-modifiable elements, ‘finally’ is used in exception handling to execute code regardless of an exception being thrown, and ‘finalize’ is a special method called by the garbage collector before an object is reclaimed. It is important to understand the differences between these three keywords to ensure proper usage in your Java programs.

  1. Oracle’s Java documentation on the final keyword
  2. Oracle’s Java documentation on the finally keyword
  3. Oracle’s Java documentation on the finalize() method

--

--

Alexander Obregon

Software Engineer, fervent coder & writer. Devoted to learning & assisting others. Connect on LinkedIn: https://www.linkedin.com/in/alexander-obregon-97849b229/