Difference between final, finally and finalize

Ans)

final - final keyword can be used with a class, variable or a method.

  • A variable declared as final acts as constant, which means one a variable is declared and assigned , the value cannot be changed. An object can also be final, which means that the once the object is created it cannot be assigned a different object, although the properties or fields of the object can be changed.
  • A final class is immutable, which means that no other class can extend from it. E.g String, Integer.
  • A final method in a class cannot be overridden in the child class.

The underlying behavior of using final keyword is to act as constant.

public class Test {
  private static final String PREFIX = "test." 
  private final MyClass obj = new Myclass();

  publc Test() {
    obj = new MyClass() ;// throws error 
  }
}
public class Test {
  private static final String PREFIX = "test." 
  private final MyClass obj;

  publc Test() {
    obj = new MyClass() ;// this works
  }
}
finally - finally keyword is used with try-catch block for handling exception. The finally block is optional in try-catch block. The finally code block is always executed after try or catch block is completed. The general use case for finally block is to close the resources or clean up objects used in try block. For e.g. Closing a FileStream, I/O stream objects, Database connections, HTTP connections are generally closed in a finally block.


public class Test {
  public static void main(String[] args) {
    BufferedReader br = null;
    try {
      String sCurrentLine = "";
      br = new BufferedReader(new FileReader("C:\\testing.txt"));
      while ((sCurrentLine = br.readLine()) != null) {
        System.out.println(sCurrentLine);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally { // close the resource. 
      try {
        if (br != null)br.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
}

finalize() - This is the method of Object class.It is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like file handles, sockets, database connections etc because Java has only a finite number of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method.

Most Viewed Posts