Hiprup

What is the difference between final, finally, and finalize?

Three keywords that look alike but do completely different things.

final — a modifier. final variables can't be reassigned, final methods can't be overridden, final classes can't be extended.

finally — a block in try/catch that always runs (except on JVM exit), used for cleanup like closing streams.

finalize() — a deprecated Object method called by the GC before reclaiming an object. Unreliable; use try-with-resources or Cleaner instead.

// final
final int MAX = 100;           // Constant
// MAX = 200;                   // Compile error!

final class ImmutablePoint {    // Cannot be extended
    private final int x, y;     // Cannot be reassigned
    public ImmutablePoint(int x, int y) { this.x = x; this.y = y; }
}

// finally
try {
    Connection conn = getConnection();
    // database operations
} catch (SQLException e) {
    log.error("DB error", e);
} finally {
    conn.close(); // Always executes
}

// Better: try-with-resources (replaces finally for cleanup)
try (Connection conn = getConnection();
     PreparedStatement ps = conn.prepareStatement(sql)) {
    // auto-closed when block exits
}

final makes MAX a constant, ImmutablePoint unextendable, and its fields unmodifiable after construction. The finally block closes the connection regardless of success/failure. try-with-resources is the modern alternative that auto-closes resources implementing AutoCloseable.

Know all three uses of final (variable, method, class). Mention that finalize() is deprecated — use try-with-resources or Cleaner. try-with-resources replacing finally for cleanup is the modern best practice.

What is the difference between final, finally, and finalize? | Hiprup