final — a keyword that prevents modification. finally — a block that always executes after try/catch. finalize() — a deprecated method called before garbage collection.
Analogy: final is like a locked door — once set, you can't change it. finally is like the cleanup crew that always comes in after an event, no matter what happened. finalize() is like a demolition crew that used to come before tearing down a building, but is now obsolete.
final keyword (3 uses):
1final int MAX_SIZE = 100;2MAX_SIZE = 200; // COMPILE ERROR: cannot assign a value34final String name = "Alice";5name = "Bob"; // COMPILE ERROR67// For objects, "final" means the reference can't change,8// but the object's fields CAN change:9final List<String> list = new ArrayList<>();10list.add("item"); // OK — modifying the object11list = new ArrayList<>(); // COMPILE ERROR — can't reassign reference
1class Parent {2 final void importantMethod() {3 System.out.println("This cannot be overridden");4 }5}67class Child extends Parent {8 void importantMethod() { } // COMPILE ERROR: cannot override final method9}
1final class ImmutablePoint {2 private final int x;3 private final int y;45 public ImmutablePoint(int x, int y) {6 this.x = x;7 this.y = y;8 }9 // No setters — truly immutable10}1112class SubPoint extends ImmutablePoint { } // COMPILE ERROR: cannot extend final class
finally block:
return is called in try/catch (it executes before the return).1FileInputStream fis = null;2try {3 fis = new FileInputStream("data.txt");4 // read data...5} catch (FileNotFoundException e) {6 System.err.println("File not found");7} catch (IOException e) {8 System.err.println("Read error");9} finally {10 // Always runs — close the resource11 if (fis != null) {12 try {13 fis.close();14 } catch (IOException e) {15 System.err.println("Error closing stream");16 }17 }18 System.out.println("Cleanup complete");19}2021// Better: use try-with-resources (Java 7+)22try (FileInputStream fis2 = new FileInputStream("data.txt")) {23 // read data...24} catch (IOException e) {25 System.err.println("Error: " + e.getMessage());26}27// fis2 is automatically closed here — no finally needed
finalize() method (DEPRECATED since Java 9):
protected void finalize() throws Throwable { } — inherited from Object.AutoCloseable + try-with-resources instead.1// OLD, BAD approach:2class OldResource {3 @Override4 protected void finalize() throws Throwable {5 try {6 // cleanup resources7 System.out.println("Finalize called");8 } finally {9 super.finalize();10 }11 }12}1314// MODERN approach:15class ModernResource implements AutoCloseable {16 @Override17 public void close() {18 System.out.println("Resource closed deterministically");19 }20}2122// Usage:23try (ModernResource resource = new ModernResource()) {24 // Use resource25} // close() called automatically and immediately
Why finalize() is dangerous:
Summary: final = immutable/constant. finally = always runs for cleanup. finalize() = deprecated, avoid entirely.