• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Structures » Differences between Final, Finally and Finalize in Java
Next →
← Prev

Differences between Final, Finally and Finalize in Java

By Dinesh Thakur

final: Variables are useful when you need to store information that can change as the program runs. However, there may be certain situations in the program in which the value of the variable should not be allowed to modify. It is accomplished using a particular type of variable known as the final variable. The final variable also called constant variable. It is a variable with a value that cannot modify during the execution of the program.

The Final keyword used when we want restrictions applied to a method, class, and variable. We can’t override the Final method, inherit the Final class or change the Final variable. To declare a final variable, use the final keyword before the variable declaration and initialize it with a value. Its syntax is

final datatype varName = value;
For example:
final double PI = 3.141592;

This statement declares a variable PI of type double which initialized to 3.141592, that cannot be modified. If an attempt is made to modify a final variable after it initialized, the compiler issues an error message “cannot assign a value to final variable PI.”
You can also defer the initialization of the final variable, such a final variable known as a blank final. However, it must be initialized before it used.
Final variables are beneficial when one need to prevent accidental change to method parameters and with variables accessed by anonymous class.

Now consider a program to calculate the area of the circle,

//Area of the circle
public class AreaCircle {
    public static void main(String[] args){
        int r =10;//initializing radius
        final double PI =3.141592;//final variable
        double area;
        //PI = 3.142; will generate an error
        area = PI * r * r;
        System.out.println(“Area of circle is –>”+area);
    }
}

Output: Area of the circle is — >314.1592
NOTE: It is recommended to declare a final variable in uppercase

finally: The finally block always executes when the try block exits, except System.exit(0) call. If an exception occurs inside a try block and there is no matching catch block, the method terminates without further executing any lines of code from that method. For example, suppose you may want to close a file that has opened even if your program could not read from the file for some reason. In other words, you want to close the file irrespective whether the read is successful or not. If you want that some lines of code must be executed regardless of whether or not there is matching catch block, put those lines inside the finally block.

The finally block is used to release system resources and perform any cleanup required by the code in the try block. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The finally block consist of finally keyword followed by the code enclosed in curly braces. Just like a catch block, a finally block is associated with a particular try block and must appear after the last catch block. If there are no catch blocks, then you can place the finally block immediately after the try block.

The general form of a try statement with finally block is

try {
    //statement that can throw exceptions
}
catch(exception_type identifier) {
    //statements executed after exception is thrown
}
finally {
     //statements which executed regardless of whether or not

     //exceptions are thrown
}

Let us consider three cases when the try-catch block executes only with the finally block.

Case A: If the try block succeeds (i.e., no exception is thrown), the flow of control reaches the end of the try block and proceeds to the finally block by skipping over the catch blocks. When the finally block completes, the rest of the method continues.

Case B: If a try block fails (i.e., an exception is thrown), the flow control immediately move to the appropriate catch block. When the catch block completes, the finally block runs. When the finally block completes, the rest of the method continues.

Case C: If the try or catch block has a return statement, the finally block still get executed before control transfers to its new destination. Now let us consider a program that demonstrates the use of finally block,

use of finally block

Output: divide by zero
Inside finally block
End of main method
NOTE: The finally block always executed except when the try or catch invokes a System.Exit() method, which causes the Java interpreter to stop running.

finalize(): Garbage collection automatically frees us the memory resources used by objects, but objects can hold other kinds of resources, such as open files and network collections. The garbage collector cannot free these resources for you. For this, we need to write a finalize() method for any object that needs to perform such tasks as closing files, terminating network connections and so on. The finalize() method declared in the java.lang.Object class.

A finalize() method is an instance method that takes no arguments and returns no value. There can be only one finalize() method per class. A finalize() method can throw an exception or error, but when the garbage collector automatically invokes it, any exception or error it throws is ignored and serves only to cause the method to return.

Before an object gets garbage collected, the garbage collector gives the object an opportunity to clean up itself through a call to the object’s finalize() method. This method is called automatically by Java before an object finally destroyed, and space it occupies in memory is released. The finalize() method takes the following form,

protected void finalize() {

  //clean up code by you

}

Here, the keyword protected is an access specifier that prevents access to the finalize method by code defined outside the class. This code will explain it better:

class FinalizeExample {
   public void finalize() {
      System.out.println(“Finalize is called”);
   }
   public static void main(String args[]) {
         FinalizeExample f1 = new FinalizeExample();
         FinalizeExample f2 = new FinalizeExample();
         f1 = null;
         f2 = null;
         System.gc();
   }
}

This method is useful when

• Your class object use resources that are not within the Java environment and are not guaranteed to be released by the object itself.· For example Graphics resources, fonts, etc. that are supplied by the host operating system.
• To record the fact that the object destroyed. For example: To count the numbers of objects that were in memory rather than created. Writing Java classes that interface to native platform code with native methods. In such a case, the native implementation can allocate memory or other resources that are not under the control of the garbage collector and need to reclaimed explicitly.
A problem with the finalize() method is that you never know when or if the finalize() method called. It is because the garbage collector is not guaranteed to execute at a specified time. So one should avoid using the finalize() method and when you do so you should write it with great care.

You’ll also like:

  1. Finally Block in Java with Example
  2. Differences Between C++ and Java
  3. Explain Differences Between C , C++, and Java
  4. Final Method in Java with Example
  5. Final Variable in Java Example
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW