Skip to content

Commit ecadaee

Browse files
authored
Merge pull request #2 from vardhan30016/add-new-java-question
Add: new Java interview question on difference between final, finally, and finalize()
2 parents b6de613 + edc1d02 commit ecadaee

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ Frequently asked Java Interview questions
2626
| 17 | [What is finalize method? How do you override it?](#what-is-finalize-method-how-do-you-override-it) |
2727
| 18 | [What Is the Difference Between the Comparable and Comparator Interfaces](#what-is-the-difference-between-the-comparable-and-comparator-interfaces) |
2828
| 19 | [What Is an inner class](#what-is-an-inner-class) |
29+
| 20 | [What is the difference between final, finally, and finalize() in Java?](#what-is-the-difference-between-final-finally-and-finalize-in-java) |
30+
2931
<!-- TOC_END -->
3032

3133
<!-- QUESTIONS_START -->
@@ -683,4 +685,43 @@ Frequently asked Java Interview questions
683685

684686
**[⬆ Back to Top](#table-of-contents)**
685687

688+
20. ### What is the difference between final, finally, and finalize() in Java?
689+
690+
The terms `final`, `finally`, and `finalize()` in Java look similar but serve completely different purposes.
691+
692+
1. **final**It is a **modifier** used for variables, methods, and classes.
693+
- A `final` variable cannot be reassigned once initialized.
694+
- A `final` method cannot be overridden in subclasses.
695+
- A `final` class cannot be extended.
696+
697+
2. **finally** → It is a **block** used in **exception handling** to execute important code such as closing files, releasing connections, etc.
698+
- The `finally` block executes **regardless** of whether an exception occurs or not.
699+
700+
3. **finalize()** → It is a **method** defined in the `Object` class that the **Garbage Collector** calls before destroying an object.
701+
- It is rarely used now because garbage collection timing is unpredictable.
702+
703+
**Example:**
704+
705+
```java
706+
public class FinalExample {
707+
final int VALUE = 100;
708+
709+
public final void display() {
710+
System.out.println("Final method");
711+
}
712+
713+
public static void main(String[] args) {
714+
try {
715+
System.out.println("Inside try block");
716+
} finally {
717+
System.out.println("Inside finally block");
718+
}
719+
}
720+
721+
@Override
722+
protected void finalize() throws Throwable {
723+
System.out.println("Finalize method called");
724+
}
725+
}
726+
686727
<!-- QUESTIONS_END -->

0 commit comments

Comments
 (0)