Programming





Difference between final, finally and finalize in Java

Difference between final, finally and finalize in Java

by | 27-Mar-2020
Java

Tags:

Share: 


final: final is a reserved keyword in java which can be used on variables, methods, and classes. It has a different meaning when applied to either of them.

  1. final variable cannot be modified once initialized
public class FinalVariableExample {
    public static void main(String[] args) {
        final String name = "John";
        name = "Jim"; // This will not compile.
    }
}
  1. final method cannot be overridden
class FinalMethodExample {
     final void finalMethod() {
        System.out.println("This is a final Method.");
    }
     public static void main(String[] args) {
        System.out.println("Main method.");
    }
}
class FinalClass extends FinalMethodExample {
    @Override
    void finalMethod() { // This will not compile.
        System.out.println("This Method is trying to override the finalMethod().");
    }
}
  1. final class cannot be sub-classed. We cannot extend a final class.
public final class Parent {
    public static void main(String[] args) {
    }
}
class Child extends Parent { // This will give compiler error
}

finally: finally is a block which is used in exception handling. finally block is always executed whether the program faces an exception or not.

public class FinallyExample {
    public static void main(String[] args) {
        int divisor = 0;
        int quotient = 0;
        try {
            int dividend = 300;
            quotient = dividend / divisor;
            System.out.println(""); // This will only execute if no exception in occurred
        } catch (Exception e) {
            System.out.println(quotient); // This will only execute if an exception in occurred
        } finally {
            System.out.println("finally block is executed"); // This will always execute if exception happens or not
        }
    }
}

finalize(): finalize() method is used in Garbage Collection. finalize() method is invoked just before the object is about to be garbage collected. The finalize() method can be used to perform any cleanup before the object is destroyed.

public class FinalizeExample {
    @Override
    public void finalize() {
        System.out.println("finalize() called.");
    }
    public static void main(String[] args) {
        FinalizeExample finalize = new FinalizeExample();
        finalize = null;
        System.gc();
    }
}

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.