Site icon

Difference b/w final, finally & finalize in java (with examples)

Let us discuss final, finally and finalize in java with code examples.

What is final ?

final class:

Program to demonstrate final class in java.


final class Vehicle {
	private int doors;
}

class NewVehicle extends Vehicle {
	// Cannot subclass final class
}

What is final method?

Program demonstrating final method of Person class.

class Person {
	public final void setSalary() {

	}
}

class Manager extends Person {
	public void setSalary() {
		// cannot override final method of Person class
	}
}

What is final variable?

final int salary = 100;
//Compilation error: final variable cannot be assigned
salary = 200;

finalize:

Program to demonstrate finalize method

class TestFinalize {
	public static void main(String[] args) {
		TestFinalize obj = new TestFinalize();
                System.out.println("Executing main method");
		obj = null;
		// Signal the GC to collect the garbage
		System.gc();
	}

	protected void finalize() {
		System.out.println("Executing finalize method");
	}
}

Output of finalize method:

Executing main method
Executing finalize method

finally:

Program to demonstrate finally block in java

class Student {
	public static void main(String[] arg) {

		try {
			int salary = Integer.valueOf("NumberFormatException");
		} catch (Exception exp) {
			System.out.println("Executing exception block");
		} finally {
			System.out.println("Executing finally block");
		}
	}
}

Output of finally block:

Executing exception block
Executing finally block
Exit mobile version