Uploaded by Soumya Bera

Difference between final,finally,finalize in java

advertisement
Problem Statement :  Explain the difference between final, finally, finalize in java: 
Key
Final
Final is the keyword in
java which is used for
classes, methods and
variables and it applies
some limitation to these
attributes.
2. Functionali If we place final keyword
before a variable, we can’t
ty
modify its value
throughout the program.
If placed before method it
can’t be overwritten by
any subclass and if placed
before a class that class
can’t be inherited.
1. Definition
Finally
Finalize
The finally is a keyword in java
Which is used in exception
handling and it is used to execute
code no matter if there is an
exception or not.
Finalize method in Java is an
Object Class method which is
used just before an object is
destroyed and can be called
just prior to garbage
collection.
Finalize method in java is used
Java finally block is always
executed whether an exception is to release all the resources
used by the object before it is
handled or not. Therefore, it
deleted/destroyed by the
contains all the necessary
statements that need to be printed Garbage collector.
regardless of the exception occurs
or not also finally block in Java can
be used to put clean-up code such
as closing a file, closing connection,
etc.
3. Time of
execution
Final method is executed
only when we call it.
Finally, block is executed as soon as finalize method is executed
the try-catch block is executed.
just before the object is
destroyed.
Its execution is not dependant on
the exception.
4. Applied to
Final is mainly used for
classes, methods,
variables etc
Finally, block is always related to
the try and catch block in
exception handling.
finalize () method is used with
the objects.
5. Example
import java.util.*;
public class Finally {
public static void main(String[]
args) {
int a,b,c;
a=10;
b=0;
try{
int res = a/b;
}catch(Exception e){
System.out.println("Error: /
by 0");
}
finally{
System.out.println("Finished
.");
}
}
}
public class Finalize {
public static void
main(String[] args) {
String str1 = new
String("CS");
str1 = null;
System.gc();
System.out.println("output
of main method");
}
final class Fin{
final float pi = 3.14f;
final void circle(int r){
float area = pi*r*r;
System.out.println("Th
e area of the circle is :-->
"+area);
}
}
public class Final{
public static void
main(String[] args) {
Scanner input = new
Scanner(System.in);
System.out.println("En
ter the radius of the circle
:--> ");
int r =
input.nextInt();
input.close();
Fin obj = new Fin();
obj.circle(r);
}
}
Link:
https://www.scaler.com/topics/finalize-method-in-java/
protected void finalize()
{
System.out.println("ou
tput of finalize method");
}
}
Related documents
Download