Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
2 views6 pages

Final and Finalize

The final keyword in Java is a non-access modifier that can be applied to variables, methods, and classes to indicate that they cannot be modified or extended. Final variables are constants, final methods cannot be overridden, and final classes cannot be inherited. Additionally, the document explains the differences between final, finally, and finalize, highlighting their distinct roles in Java programming.

Uploaded by

sucharita.sit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Final and Finalize

The final keyword in Java is a non-access modifier that can be applied to variables, methods, and classes to indicate that they cannot be modified or extended. Final variables are constants, final methods cannot be overridden, and final classes cannot be inherited. Additionally, the document explains the differences between final, finally, and finalize, highlighting their distinct roles in Java programming.

Uploaded by

sucharita.sit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

final Keyword in Java

final keyword is used in different contexts. First of all, final is a non-access modifier applicable
only to a variable, a method, or a class. The following are different contexts where final is used.

Characteristics of final keyword in java:

In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified
or extended. Here are some of its characteristics:

 Final variables: When a variable is declared as final, its value cannot be changed once it
has been initialized. This is useful for declaring constants or other values that should not
be modified.
 Final methods: When a method is declared as final, it cannot be overridden by a
subclass. This is useful for methods that are part of a class’s public API and should not be
modified by subclasses.
 Final classes: When a class is declared as final, it cannot be extended by a subclass. This
is useful for classes that are intended to be used as is and should not be modified or
extended.
 Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class. This ensures that the value of the variable is set and cannot be
changed.
 Performance: The use of final can sometimes improve performance, as the compiler can
optimize the code more effectively when it knows that a variable or method cannot be
changed.
 Security: final can help improve security by preventing malicious code from modifying
sensitive data or behavior.

Overall, the final keyword is a useful tool for improving code quality and ensuring that certain
aspects of a program cannot be modified or extended. By declaring variables, methods, and
classes as final, developers can write more secure, robust, and maintainable code.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class

Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method

1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }

Output:Compile Time Error


3) Java final class
If you make any class as final, you cannot extend it.

Example of final class

1. final class Bike{}


2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }

Output:Compile Time Error

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }

Output:running...

Difference between final, finally and finalize


The final, finally, and finalize are keywords in Java that are used in exception handling. Each of
these keywords has a different functionality. The basic difference between final, finally and
finalize is that the final is an access modifier, finally is the block in Exception Handling and
finalize is the method of object class.

finalize() method in Java is used to release all the resources used by the object before it is
deleted/destroyed by the Garbage collector. finalize is not a reserved keyword, it's a method.
Once the clean-up activity is done by the finalize() method, garbage collector immediately
destroys the Java object.
Along with this, there are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:

Sr.
Key final finally finalize
no.

final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
1. Definition used to apply restrictions execute the important code clean up processing just
on a class, method or whether the exception before object is garbage
variable. occurs or not. collected.

Final keyword is used with Finally block is always


finalize() method is used
2. Applicable to the classes, methods and related to the try and catch
with the objects.
variables. block in exception handling.

(1) Once declared, final


(1) finally block runs the
variable becomes constant
important code even if finalize method performs the
and cannot be modified.
exception occurs or not. cleaning activities with
3. Functionality (2) final method cannot be
(2) finally block cleans up all respect to the object before
overridden by sub class.
the resources used in try its destruction.
(3) final class cannot be
block
inherited.

Finally block is executed as


soon as the try-catch block
is executed. finalize method is executed
Final method is executed
4. Execution just before the object is
only when we call it.
It's execution is not destroyed.
dependant on the
exception.

Java final Example


Let's consider the following example where we declare final variable age. Once declared it
cannot be modified.

FinalExampleTest.java

1. public class FinalExampleTest {


2. //declaring final variable
3. final int age = 18;
4. void display() {
5.
6. // reassigning value to age variable
7. // gives compile time error
8. age = 55;
9. }
10.
11. public static void main(String[] args) {
12.
13. FinalExampleTest obj = new FinalExampleTest();
14. // gives compile time error
15. obj.display();
16. }
17. }

Output:

In the above example, we have declared a variable final. Similarly, we can declare the methods
and classes final using the final keyword.

Java finally Example


Let's see the below example where the Java code throws an exception and the catch block
handles that exception. Later the finally block is executed after the try-catch block. Further, the
rest of the code is also executed normally.

FinallyExample.java

1. public class FinallyExample {


2. public static void main(String args[]){
3. try {
4. System.out.println("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. System.out.println(data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. System.out.println("Exception handled");
12. System.out.println(e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. System.out.println("finally block is always executed");
17. }
18. System.out.println("rest of the code...");
19. }
20. }

Output:

Java finalize Example


FinalizeExample.java

1. public class FinalizeExample {


2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. System.out.println("Hashcode is: " + obj.hashCode());
7. obj = null;
8. // calling the garbage collector using gc()
9. System.gc();
10. System.out.println("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. System.out.println("Called the finalize() method");
16. }
17. }

Output:

You might also like