Difference between final, finally and finalize

 

Every java interview might have this question asked for a beginner. Probably this is the most known question and well sort for answers. Though there are tons of other articles explaining the differences about these, I am planning to put those difference in a slightly different and more understandable. I am expecting that I will definitely reach my objective, while it’s the perception of the reader that is really important.

S.No final finally finalize
1 Is a keyword Is a keyword Is a method
2 Is a non access modifier Is used in exception handling Is used in object destruction / garbage collection
3 Used in defining variables, classes and methods Used in combination with try, catch clauses. Not frequently used by user in programming. Called from Garbage collector.

In addition to the above differences I will put some more usage of each below.

final:

Using it on a variable will make sure it only can be instantiated and never modified.

	private final int age = 23;
	private final Person person = new Person(age);
	public class Person{
		int age;
		private Person(int age){		
			this.age = age;
		}
	}
  • The variables “person” and “age” will never change, as they are declared as final. What does this mean is, if you try assigning a different value for age like setting it to “age = 25” anywhere else will cause a compilation error.

Similarly assigning a different value for “person” will also result in the same issue. While you are free to change the state of the person object, like executing a statement like “person.age=25” is pretty legal, and you will not get any compilation errors.

  • Generally the “final” keyword is combined with “static” keyword to create “Constants”.
  • Also, by default the variables in an Interface are always public final static by default.

Note:  This question on stack overflow might interest you, as it is about the combination of JRE default value assignments to instance variables declared final.

Using final keyword on method definitions and method parameters

  • “final” keyword in a method will make sure the method is never overridden, by its children.
  • final methods are used, when you don’t want the functionality be changed at any point.

Ex: In java, Object class defines getClass() method as final, as it makes sure the implementation of it will never change.

public final Class getClass()

Using final keyword on a class definition

  • “final” keyword when decorated on a class, make it can never be inherited.

Ex: In java, Math class defines itself as final. Hence it cannot be inherited or its functionality will never be overridden.

public final class Math
extends Object

finally:

  • “finally” is a keyword that is used in the exception handling. It makes sure that a set of statements to be executed irrespective of the occurrence of the exception in the try block.
  • statements in the finally block will be executed, even when the try block returns the method.
  • finally can be used along with handling catch clause or by simply after try, which will be executed and the exception is thrown to the caller.

“I believe 10 lines of code helps better than 100 lines of statements / theory”, hence the following code and output.

	static class TestFinally {
		private void sample() {
			try {
				System.out.println("Throwing exception in sample1");
				throw new RuntimeException();
			} catch (Exception ex) {
				System.out.println("Exception handled in sample1");
			} finally {
				System.out.println("Finally executed in sample1");
			}
		}

		private void sample2() {
			try {
				System.out.println("Throwing exception in sample2");
				throw new RuntimeException();
			} finally {
				System.out.println("Finally executed in sample2");
			}
		}

		private void sample3() {
			try {
				System.out.println("Returning in try block");
				return;
			} finally {
				System.out.println("Finally executed in sample3");
			}
		}
	}

	public static void main(String[] aa) {
		TestFinally instance = new TestFinally();
		try {
			instance.sample();
		} finally {
			System.out.println("Finally in main thread for sample1 completed");
		}
		try {
			instance.sample2();
		} catch (Exception e) {
			System.out.println("Exception caught from sample2");
		}
		instance.sample3();

	}

Output:

Throwing exception in sample1
Exception handled in sample1
Finally executed in sample1
Finally in main thread for sample1 completed
Throwing exception in sample2
Finally executed in sample2
Exception caught from sample2
Returning in try block
Finally executed in sample3

finalize:

  • finalize is a method in “java.lang.Object” class.
  • finalize method is called by the Garbage collector, when there are no references to this object.
  • time of execution of the finalize method on an object cannot be guaranteed, as the Garbage Collector execution is not guaranteed. Smile
  • Calling object.finalize() will not ensure the object is sent for garbage collection immediately. (A common myth of all novice programmers).
  • finalize method can be overridden, to execute a set of steps when this object is sent for GC. Though I never had any use case to override it with a different behavior than the default.

Hope this information was helpful, as I always say your comments will help me understand and improve my blogging skills, and hence will request you to definitely leave a comment even though you find it use[ful|less].

Advertisements

About Sharath

I am a passionate technologist, I have varied interests in Development, Testing and Maintenance phases of PDLC / SDLC. In my leisure I love to play with my daughter. I love eating out, hanging out with friends and reading blogs/articles.
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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s