What is final, finally and finalize ?

Final

  • Final is used to apply limitations on class, method and variable. Final variable value couldn’t be changed final method couldn’t be overridden and final class can’t be inherited.
  • Final is a keyword.

Sample Code

  • Once initialized value of variable cannot be changed.
class A 
{
public static void main(String[] args)
{
int a = 5;

// final variable
final int b = 6;


a++;

// modifying the final variable :
b++;
}
}
  • If we declare any variable as final, we can’t change its contents since it is final, and if we change it then we have the Compile Time Error.

Finally

  • Finally is used to place significant code, whether exception is handled or not that time will be executed.
  • Finally is a block.

Sample Code

// A Java program to demonstrate finally. 
class Wikitechy
{

static void A()
{
try
{
System.out.println("inside A");
throw new RuntimeException("demo");
}
finally
{
System.out.println("A's finally");
}
}
static void B()
{
try
{
System.out.println("inside B");
return;
}
finally
{
System.out.println("B's finally");
}
}

public static void main(String args[])
{
try
{
A();
}
catch (Exception e)
{
System.out.println("Exception caught");
}
B();
}
}

Output

inside A
A's finally
Exception caught
inside B
B's finally

Finalize

  • Finalize is using for the processing of clean up to be perform just before object is garbage collected.
  • Finalize is a method.
  • Once finalize method completes immediately Garbage Collector destroy that object.

Syntax

protected void finalize throws Throwable
{

}

Sample Code

class Wikitechy 
{
public static void main(String[] args)
{
String s = new String("RR");
s = null;

// Requesting JVM to call Garbage Collector method
System.gc();
System.out.println("Main Completes");
}

// Here overriding finalize method
public void finalize()
{
System.out.println("finalize method overriden");
}
}

Output

Main Completes

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,