Home>

The difference between final, finally and finalize in java

1.final can modify classes,Cannot be inheritedCan modify methods,Cannot be rewrittenCan modify variables,Can only be assigned once.

2.finally is the body of the try statement,Cannot be used alone,Used to release resources;

3.finalize is a method,When the garbage collector determines that there are no more references to the object,This method is called by the object's garbage collector.

The following code program:

package cn.jit.test;
/**
 * Interview question 1:Difference between final, finally and finalize:
 *
 * final can modify classes,Cannot be inherited;
 * Methods can be modified,Cannot be rewritten
 * Can modify variables,Can only be assigned once.
 * finally is the body of the try statement,Cannot be used alone,Used to release resources;
 * finalize is a method,When the garbage collector determines that there are no more references to the object,By object
 * 'S garbage collector calls this method.
 *
 *
 * Interview Question 2:If there is a return statement in the catch, will the finally code still be executed?
 * If yes, is it before return or after return?
 * meeting. Before return.
 *
 * @author rocky
 *
 * /
public class finallydemo8 {
  public static void main (string [] args) {
    demo d=new demo ();
    system.out.println (d.method ());
  }
}
class demo {
  public int method () {
    int x=10;
    try {
      x=20;
      system.out.println (1/0);
      return x;
    } catch (exception e) {
      x=30;
      return x;
    } finally {
      /*
       * There should be no return statement in finally
       * Otherwise the method will definitely return what is here
       * /
      x=40;
      return 40;
      //Never write a return statement in finally,Because the role of finally is
      //Release resources,Will definitely be executed,If you write a return statement in it,Then try and cache
      //the result will be changed,So writing this is a crime! !! !!
    }
  }
}
  • Previous jquery like function to implement the code like it!
  • Next AngularJS basic ng-if instruction usage