---
title: "What are finally and finalize in Java?"  
description: "What are finally and finalize in Java?"  
author: "Mukul Goenka"  
published: 2021-11-24  
updated: 2023-06-16  
canonical: https://www.mindstick.com/interview/33848/what-are-finally-and-finalize-in-java  
category: "java"  
tags: ["java", "programming language"]  
reading_time: 2 minutes  

---

# What are finally and finalize in Java?

**Finally** block is used with a try-catch block to put the code that you always want to get executed even the execution is thrown by the try-catch block. Finally is just used for releasing the resources which were created by the try block.

**Finalize()** is a special method in Object class that we can override in our classes. Finalize() is called by the Garbage collector to collect the garbage value when the object is getting it. This method is generally overridden to release the system resources when garbage value is collected from the object.

## Answers

### Answer by Aryan Kumar

**Finally** and **finalize** are two keywords in Java that are used for exception handling and garbage collection, respectively.

**Finally** is a block of code that is always executed, regardless of whether or not an exception is thrown. This can be used to ensure that important cleanup code is always executed, even if an exception is thrown and the rest of the code in the try block is not executed.

**Finalize** is a method that is called by the garbage collector when an object is about to be garbage collected. This method can be used to perform cleanup tasks on the object, such as closing files or releasing other resources.

Here is an example of how to use the finally keyword:

Code snippet

```plaintext
try {
  // Do something that might throw an exception.
} finally {
  // This code will always be executed, even if an exception is thrown.
}
```

Here is an example of how to use the finalize method:

Code snippet

```plaintext
public class MyObject {

  @Override
  protected void finalize() throws Throwable {
    // Do something to clean up before the object is garbage collected.
  }

}
```

### Answer by Mukul Goenka

**Finally** block is used with a try-catch block to put the code that you always want to get executed even the execution is thrown by the try-catch block. Finally is just used for releasing the resources which were created by the try block.

**Finalize()** is a special method in Object class that we can override in our classes. Finalize() is called by the Garbage collector to collect the garbage value when the object is getting it. This method is generally overridden to release the system resources when garbage value is collected from the object.


---

Original Source: https://www.mindstick.com/interview/33848/what-are-finally-and-finalize-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
