Differences among final, finally and finalize in Java is an important interview question. One reason being, these words sound similar and another is it gives an interviewer a chance to branch out to many other areas. From final you can go on to talk about inheritance or method overriding. From finally you can start about exception handling. From finalize method you can talk about Object class. So you see just one question final Vs finally Vs finalize in Java has such a huge potential!
Now, when the importance of these words final
, finally
and finalize
in Java is firmly established let’s try to get some details about them.
One point where they differ is both final and finally are reserved keywords in Java on the other hand finalize() is a method. Though when you talk about finally you generally say finally block as you will write a block of code enclosed with in a scope of finally.
final Vs finally Vs finalize in Java
final– final keyword restricts the access to variable, method or class.
When final is used with a variable the value of that variable can’t be changed once initialized.
When a method is declared as final that method can’t be overridden by any subclass.
When a class is declared as final that class can’t be extended.
Refer final in Java to know more about final keyword in Java.
final variable examplepublic class FinalVar { public static void main(String[] args) { final int test = 7; // modifying final variable test++; } }
Here test is a final variable so changing its value will result in a compile time error “The final local variable test cannot be assigned. It must be blank and not using a compound assignment”.
final method exampleclass Read { public final void readFile() throws IOException{ System.out.println("read file"); } } public class FileRead extends Read { // Overridden method public void readFile() throws IOException{ File file = new File("D://test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); } }
Here readFile() is marked as final in the parent class Read so trying to override it in child class FileRead will result in a compile time error “Cannot override the final method from Read”.
final class examplefinal class Read { public void readFile() throws IOException{ System.out.println("read file"); } } public class FileRead extends Read { ... ... }
Here class Read is marked as final so it can’t be subclassed. Class FileRead trying to extend Read class will result in compile time error “The type FileRead cannot subclass the final class Read”.
finally– finally keyword is part of exception handling in Java. It is used along with try-catch block. The code enclosed with in a finally block is always executed whether an exception is thrown in the code enclosed in try block or not.
In case no exception is thrown inside the try block, finally block is executed when try block exists.
When exception is thrown in a try block if there is a catch block that matches the exception type of the thrown exception that catch block is executed first and then the finally block.
In case catch block can’t handle the thrown exception finally block is still executed just before the method returns.
Because of the guarantee that finally block will always be executed it is used for putting clean up code. If in the code you have any input or output stream crated for reading or writing a file or there are opened DB connections then finally block is the safe place to close these resources.
Finally Java example programpublic class FileRead { public void readFile(){ BufferedReader br = null; try{ br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("D:\\test1.txt")))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { FileRead fr = new FileRead(); fr.readFile(); } }
finalize– finalize() method is called by the garbage collector thread just before garbage collecting any object.
finalize method is present in Object class as a protected method, it’s syntax is as follows-
protected void finalize() throws Throwable
Since finalize method is in Object class so it is inherited by every class in Java. The finalize method in Object class has no implementation so the class, where some clean up is required, has to override it to perform clean up or to dispose of system resources.
Finalize method Java examplepublic class FinalizeExample { int num; FinalizeExample(int num){ this.num = num; } public static void main(String[] args) { FinalizeExample obj1 = new FinalizeExample(5); FinalizeExample obj2 = new FinalizeExample(5); // object reference set as null explicitly // that makes it eligible for garabge collection obj1 = null; obj2 = null; // System.gc() call request to run garbage collector System.gc(); } @Override protected void finalize() throws Throwable { System.out.println("finalize method called for FinalizeExample object"); } }Output
finalize method called for FinalizeExample object finalize method called for FinalizeExample object
That's all for the topic final Vs finally Vs finalize in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Multiple Catch Blocks in Java
- InputMismatchException in Java and Resolution
- Java var Type (Local Variable Type Inference)
- Java HashMap computeIfPresent() With Examples
- Java Stream - Get Last Element
- Create a Date Object With Values in Java
- HDFS Data Flow – File Read And Write in HDFS
- Spring @DependsOn Annotation
No comments:
Post a Comment