In your java journey sometimes you confuse about these three final words. but now we remove this confusion in this article. so lets go differentiate these three terms.
What is final, finally and finalize in simple terms?
Final :-
Final is keyword in java. final means it can not be changeable.
We can use final keyword in following three cases:-
- Final Class
- Final Variable
- Final Method
If we declare class as final then we can not extends that class. if we try to extends final class then we get error.
If we declare variable as final means we can not reassign its value means we can not change if we declare variable final.
And last id we declare method as final then we can not override that methods. means can not overridden final method.
I created full article about Final keyword in java you can check here.
Finally :-
Finally is block in java. It is simple block.
Finally {
// Finally block
System.out.print("In finally block");
}
Finalize :-
Finalize is method in java. Finalize method is available in Object class.
Finalize method is called before object is destroyed in java.
So we discuss in simple term what is final, finally and finalize so now lets see in brief using example so you can understand better.
Final Keyword:-
You can refer this for final keyword in java. in this i explain briefly what is final keyword, class, variable, method.
Finally Block :-
Finally block is used with try catch block. try catch block are used for exception handling in java.
Finally block executed always if exception caught or not. so finally block is used when you want to do something if exception occurred or not.
Can we use finally block without catch block in java?
Yes, in java we can also use finally block without catch block.
Finally block is used to execute important code like free memory usages, cleanup resource, etc. So used this kind of code in finally block is good practice.
So lets see example.
Example 1 :- Finally block when exception not caught means exception not occurred.
public class FinallyDemo {
public static void main(String[] args) {
int number1 = 10;
int number2 = 10;
int answer;
try {
System.out.println("In try block");
answer = number1 / number2;
} catch(Exception e) {
System.out.println("Exception occurred");
} finally {
System.out.println("Finally");
System.out.println("It is always executed if error caught or not");
}
}
}
public static void main(String[] args) {
int number1 = 10;
int number2 = 10;
int answer;
try {
System.out.println("In try block");
answer = number1 / number2;
} catch(Exception e) {
System.out.println("Exception occurred");
} finally {
System.out.println("Finally");
System.out.println("It is always executed if error caught or not");
}
}
}
Output :-
In try block
Finally Block.
It is always executed if error caught or not.
Finally Block.
It is always executed if error caught or not.
In above example exception is not occurred but Finally block executed.
Now lets see how finally block work when exception is caught.
Example 2 :- Finally block when exception caught by catch block
Example 2 :- Finally block when exception caught by catch block
public class FinallyDemo {
public static void main(String[] args) {
int number1 = 10;
int number2 = 0;
int answer;
try {
System.out.println("In try block");
answer = number1 / number2;
} catch(Exception e) {
System.out.println("Exception occurred: " + e);
} finally {
System.out.println("Finally Block.");
System.out.println("It is always executed if error caught or not.");
}
}
}
public static void main(String[] args) {
int number1 = 10;
int number2 = 0;
int answer;
try {
System.out.println("In try block");
answer = number1 / number2;
} catch(Exception e) {
System.out.println("Exception occurred: " + e);
} finally {
System.out.println("Finally Block.");
System.out.println("It is always executed if error caught or not.");
}
}
}
Output :-
In try block
Exception occurred: java.lang.ArithmeticException: / by zero
Finally Block.
It is always executed if error caught or not.
Exception occurred: java.lang.ArithmeticException: / by zero
Finally Block.
It is always executed if error caught or not.
In above example DivideByZero exception is caught by catch block but finally block also executed.
Finalize Method :-
- Finalize method defined in java.lang.Object class which is parent of all java classes.
- Finalize method is execute before object is destroyed like we discuss above.
- In simple term, finalize method called before garbage collection on particular object.
- Finalize method called by garbage collector when object are not referenced anywhere in code and have been selected for garbage collection. means object that are not used anymore.
- Finalize method calls only once by Garbage Collector thread. If object revives from finalize method then finalize method does not call again.
Finalize get invoked when JVM (Java Virtual Machine) find out that particular object should be garbage collected.
Syntax of finalize method:-
protected void finalize throws Throwable { }
For call garbage collection manually we have to call gc() method. so lets see example of that.
public class FinalizeDemo {
public static void main(String[] args)
{
FinalizeDemo obj = new FinalizeDemo ();
System.out.println(obj.hashCode());
public static void main(String[] args)
{
FinalizeDemo obj = new FinalizeDemo ();
System.out.println(obj.hashCode());
// Set object to null so it is garbage collected.
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");
System.out.println(obj.hashCode());
System.gc();
System.out.println("end of garbage collection");
System.out.println(obj.hashCode());
}
}
}
Output :-
617901222
end of garbage collection
Exception in thread "main" java.lang.NullPointerException
at FinalizeDemo.FinalizeDemo.main(FinalizeDemo .java:13)
end of garbage collection
Exception in thread "main" java.lang.NullPointerException
at FinalizeDemo.FinalizeDemo.main(FinalizeDemo .java:13)
We created object of FinalizeDemo class and print hash code of that object. after we set null to object so we can call garbage collector for clear that object after set null we call gc method for garbage collected.
Finally after cleared that object if we again call hashCode method we get error because that object is clear from memory.
When Finalize method called in Java?
In simple term, The finalize method will be called after the Garbage Collector detects that the object
is no longer reachable, and before it actually reclaims the memory used
by the object.
Check out this for more info.
Why we override finalize method in java?
In general it is best practice to not rely on finalize() method to do any clean up activity.
In general it's best not to rely on
finalize()
to do any cleaning up etc.- You should override finalize when your class has resources
that won't be cleaned up by the Garbage Collector, such as file handles or database
connections.
- When you set available object references to null
after the purpose of creating the object is done.
- When you make the reference variable to refer to another object.
Check out StackOverflow answers for more info :-
Check java doc for more.
if you want to learn more about Finalize method check this article :-
OTHER ARTICLES YOU MAY LIKE :-
- Double Brace Initialization in Java
- BiFunction in Java
- Lambda Expression in Java
- Functional Interface in Java
- Abstraction in Java
- Static in Java (Static class, Method, Variable and Block)
- Final keyword in java
If you want to learn coding for FREE follow this link :-
Comments
Post a Comment