What are the differences between final, finally, and finalize in Java?
161
18-Jul-2024
Ravi Vishwakarma
18-Jul-2024final
KeywordThe
final
the keyword is used to define constants and prevent method overriding, and inheritance. It can be applied to variables, methods, and classes.Read more - What is the difference between static and final keywords in Java?
finally
BlockThe
finally
block is used in conjunction withtry
andcatch
blocks for exception handling. It ensures that a block of code is executed regardless of whether an exception is thrown or not. This is typically used for cleanup activities like closing files, releasing resources, etc.finalize
MethodThe finalize method is used to perform cleanup operations before an object is garbage collected. This method is defined in the Object class and can be overridden by subclasses. However, it is generally not recommended to rely on finalizing it for cleanup due to its unpredictability and performance costs.
Summary of Differences:
final
finally
finalize
try-catch
blockfinal int x = 10;
final void method() {}
final class MyClass {}
try { ... } catch (Exception e) { ... } finally { ... }
protected void finalize() throws Throwable { ... }
Bitwise AND, OR, XOR, and left/right shift operations.
What is the difference between JDK, JRE, and JVM?
Discuss the differences between deep copy and shallow copy in Java objects.