Final vs Finally in Java: Key Differences & Usage Guide

final is a Java keyword that locks a variable, method, or class from ever changing; finally is a block that always runs after a try-catch, even if an exception flies or a return jumps out.

Imagine booking the last seat on a flight—final is your seat number that can’t be reassigned. finally is the crew that still walks the aisle after turbulence, ensuring bags are stowed no matter what happens in the air.

Key Differences

final freezes reference or behavior: once a reference is final, it always points to the same object. finally guarantees cleanup: it executes after try-catch, even on System.exit attempts, making it perfect for closing files or releasing locks.

Which One Should You Choose?

Use final when you want immutability—constants, thread-safe fields, or secure method overrides. Use finally when you need reliable cleanup—closing sockets, rolling back transactions, or logging end-of-method stats regardless of success or failure.

Examples and Daily Life

final int TIMEOUT = 30; // constant
try { connect(); } catch(IOException e) { log(e); } finally { socket.close(); } // always runs

Can a final variable be reassigned inside a finally block?

No. final variables are immutable once set; the finally block cannot change their reference, only interact with their state.

Is finally executed after return in the try block?

Yes. finally runs before control returns to the caller, letting you release resources even when the method exits early.

Can I omit finally if I use try-with-resources?

For auto-closeable resources, yes; try-with-resources handles closing. Use finally only for non-autocloseable cleanup like manual locks or custom rollback.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *