Thursday, May 3, 2018

Difference between final, finally and finalize()

final:
  • final is a keyword
  • final is used to apply restrictions on class, method and variable
  • final class cannot be inherited
  • final method cannot be overriden
  • final variable value cannot be changed
  1. class FinalExample {
  2. public static void main(String[] args) {
  3. final int x = 100;
  4. x = 200;// Compile Time Error
  5. }
  6. }
finally:
  • finally is a block
  • finally block always execute, whether exception is handled or not
  • in one scenario finally block doesn't execute is System.exit(0);
  1. class FinallyExample {
  2. public static void main(String[] args) {
  3. try {
  4. int x = 300;
  5. } catch (Exception e) {
  6. System.out.println(e);
  7. } finally {
  8. System.out.println("finally block is executed");
  9. }
  10. }
  11. }
finalize():
  • finalize() is a method
  • finalize is used to perform clean up processing just before object is garbage collected
  1. class FinalizeExample {
  2. public void finalize() {
  3. System.out.println("finalize called");
  4. }
  5. public static void main(String[] args) {
  6. FinalizeExample f1 = new FinalizeExample();
  7. FinalizeExample f2 = new FinalizeExample();
  8. f1 = null;
  9. f2 = null;
  10. System.gc();
  11. }
  12. }

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...