Câu hỏi phỏng vấn Java
Câu hỏi

How does finally block differ from finalize() method?

Câu trả lời

The finally block and the finalize() method in Java serve different purposes and are used in different contexts within the language.

finally Block

The finally block is a key component of Java's exception handling mechanism. It is always associated with a try block and optionally a catch block. The primary purpose of the finally block is to execute a section of code regardless of whether an exception is thrown or not. This ensures that certain essential cleanup operations are performed, such as releasing resources like file handles or database connections, even if an error occurs during the execution of the code within the try block. The finally block is executed after the try and any corresponding catch blocks have completed, regardless of the outcome—whether an exception was caught, not caught, or if a return statement was encountered within the try or catch blocks[1][2][3][4][6].

finalize() Method

On the other hand, the finalize() method is a protected method of the Object class in Java, which is invoked by the garbage collector on an object when the garbage collector determines that there are no more references to the object. The purpose of finalize() is to give an object one last chance to release any system resources or perform other cleanup before the object is re...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

How do you ensure that N threads can access N resources without deadlock?

middle

What are Scriptlets in Java?

middle

What are the steps involved to make work a RMI program?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào