final, finally and finalize in Java



  • The final keyword can be used with class method and variable. A final class cannot be inherited, a final method cannot be overridden and a final variable cannot be reassigned.

  • The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you just wish to execute, despite what happens within the protected code.

  • The finalize() method is used just before object is destroyed and can be called just prior to object creation.

Example final

public class Tester {    final int value = 10;    // The following are examples of declaring constants:    public static final int BOXWIDTH = 6;    static final String TITLE = "Manager";    public void changeValue() {       value = 12; // will give an error    }    public void displayValue(){       System.out.println(value);    }    public static void main(String[] args) {       Tester t = new Tester();       t.changeValue();       t.displayValue();    } }

Output

Compiler will throw an error during compilation.

Tester.java:9: error: cannot assign a value to final variable value value = 12; // will give an error ^ 1 error

Example finally

public class Tester {    public static void main(String[] args) {       try{          int a = 10;          int b = 0;          int result = a/b;       }catch(Exception e){          System.out.println("Error: "+ e.getMessage());       }       finally{          System.out.println("Finished.");       }    } }

Output

Error: / by zero Finished.

Example finalize

public class Tester {    public void finalize() throws Throwable{       System.out.println("Object garbage collected.");    }    public static void main(String[] args) {       Tester t = new Tester();       t = null;       System.gc();    } }

Output

Object garbage collected.
Updated on: 2021-07-29T14:01:06+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements