Final, finally and finalize in java

final:

final in java represents a keyword which can be used to apply restrictions on variable, method and class. It can be used with instance variables, local variables, methods and classes.

Important points

  • If we use final with class then it would not be possible to extend that class i.e. Final class will not be inherited.
  • If we use final with method then it it would not be possible to override that method i.e. Final methods can not be overridden.
  • If we use final with a instance variable, a local variable or a parameter then it cannot be changed. Note: If the reference is pointing to a mutable object then internal state of mutable object could be changed despite being final.

Example: final with instance variable

public class Main
{   
    int instanceVariable1 = 10;
    final int instanceVariable2 = 20;
 
    void showValues() {
        System.out.println("instanceVariable1: " + instanceVariable1);
        System.out.println("instanceVariable2: " + instanceVariable1);
        instanceVariable1 = 12; // Will work
        instanceVariable2 = 30; // Compilation error will occur
        System.out.println("instanceVariable1: " + instanceVariable1);
        System.out.println("instanceVariable2: " + instanceVariable1);
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.showValues();
	}
}

Output

Main.java:10: error: cannot assign a value to final variable instanceVariable2
        instanceVariable2 = 30; // Compilation error will occur
        ^
1 error

Example: final with local variable

public class Main
{  
    void showValues() {
        int instanceVariable1 = 10;
        final int instanceVariable2 = 20;
        System.out.println("instanceVariable1: " + instanceVariable1);
        System.out.println("instanceVariable2: " + instanceVariable1);
        instanceVariable1 = 12; // Will work
        instanceVariable2 = 30; // Compilation error will occur
        System.out.println("instanceVariable1: " + instanceVariable1);
        System.out.println("instanceVariable2: " + instanceVariable1);
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.showValues();
	}
}

Output

Main.java:9: error: cannot assign a value to final variable instanceVariable2
        instanceVariable2 = 30; // Compilation error will occur
        ^
1 error

Example: final with method

class ShowTest{
    final void showValues() {
        System.out.println("Inside superclass method.");
    }
}
 
public class Main extends ShowTest
{  
    void showValues() {
        System.out.println("Inside subclass method.");
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.showValues();
	}
}

Output

Main.java:9: error: showValues() in Main cannot override showValues() in ShowTest
    void showValues() {
         ^
  overridden method is final
1 error

Example: final with class

final class ShowTest{
    void showValues() {
        System.out.println("Inside superclass method.");
    }
}
 
public class Main extends ShowTest
{  
    void showValues() {
        System.out.println("Inside subclass method.");
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.showValues();
	}
}

Output

Main.java:7: error: cannot inherit from final ShowTest
public class Main extends ShowTest
                          ^
1 error

finally

finally in java represents a block which is mainly used to do clean-up task. It always execute whether the exception occur or not execpt only in case some fatal error cause program to abort or program exits using System.exit(). It is always followed by either catch or try block.
Note: Only one finally block can be associates with try block.

Example: finally with try and catch blocks

public class Main
{  
    void doDivision(int num1, int num2) {
        try {
            System.out.println("Inside try block");
            int result = num1/num2;
            System.out.println("Result: " + result);
        } catch (Exception e) {
            System.out.println("Inside catch block");
        } finally {
            System.out.println("Inside finally block");
        }
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.doDivision(25, 0);
	}
}

Output

Inside try block
Inside catch block
Inside finally block

Example: finally with try block

public class Main
{  
    void doDivision(int num1, int num2) {
        try {
            System.out.println("Inside try block");
            int result = num1/num2;
            System.out.println("Result: " + result);
        } catch (Exception e) {
            System.out.println("Inside catch block");
        } finally {
            System.out.println("Inside finally block");
        }
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.doDivision(25, 0);
	}
}

Output

Inside try block
Inside finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero   
        at Main.doDivision(Main.java:6)
        at Main.main(Main.java:14)

Example: finally with try block (no exception case)

public class Main
{  
    void finallyTest() {
        try {
            System.out.println("Inside try block");
        } finally {
            System.out.println("Inside finally block");
        }
    }
	public static void main(String[] args) {
		Main main = new Main();
		main.finallyTest();
	}
}

Output

Inside try block
Inside finally block

finalize:

finalize in java represents a method. The finalize() method is called by run-time system just before an object is collected by garbage collector. It normally contains system resources release code.
Example

public class Main
{  
    @Override
    protected void finalize() throws Throwable {
        System.out.println("Inside finalize method");
        super.finalize();
    }
 
    public static void main(String[] args) throws Exception {
		Main object = new Main();
        object = null;
        System.gc();
        Thread.sleep(2000);
	}
}

Output

Inside finalize method

Java interview questions on Exception Handling