Final, finally and finalize

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

Despite their similar sounding names, final, finally and finalize have very different purposes. To speak in very general terms, final is used to control whether a variable, method, or class is “changeable.” The finally keyword is used in a try/ catch block to ensure that a segment of code is always executed. The finalize() method is called by the garbage collector once it determines that no more references exist.

Further detail on these keywords and methods is provided below.

Final

The final statement has a different meaning depending on its context.

1.When applied to variable(primitive): The value of the variable cannot change.

2. When applied to a variable(reference): The reference variable cannot point to any other object on the heap.

3. When applied to a method: The method cannot be overridden.

4. When applied to a class: The class cannot be subclassed.

Finally

There is an optional finally block after the try block or after the catch black. Statements in the finally block will always be executed (except if Java Virtual Machine exists from the try black). The finally black is used to write the clean-up code.

Finalize

The finalize() method is called by the garbage collector when it determines that no more references exist. It is typically used to clean up resources, such as closing a file.

Advertisements
This entry was posted in JAVA. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s