Sobes.tech
Junior — Middle

What is the difference between using the final keyword and the finally block in programming languages?

sobes.tech AI

Answer from AI

In Java, the keyword final and the block finally serve completely different functions:

  • final is a modifier used for:
    • Variables: their value cannot be changed after initialization.
    • Methods: the method cannot be overridden in a subclass.
    • Classes: the class cannot be inherited.

Example:

final int x = 10;
// x = 5; // Compilation error

final class MyClass {}
// class SubClass extends MyClass {} // Error
  • finally is a block in a try-catch construct that always executes, regardless of whether an exception was thrown or not. It is usually used for resource cleanup.

Example:

try {
    // code
} catch(Exception e) {
    // exception handling
} finally {
    // code that will always execute
}
What is the difference between using the final… - sobes.tech