Skip to content
LOCZH/安大略 · 加拿大待机OK/--:--:--EST
M4M4RK_YUportfolio
  • 项目
    项目Overview
    • 作品精选案例与项目记录
    • 游戏可玩原型与游戏开发日志
  • 影像
    影像Overview
    • 档案影像合集与视觉实验
    • 商店印刷品、海报和限量物件
  • 日志
    日志Overview
    • 博客长篇开发日志与现场笔记
    • 笔记短观察、链接与代码片段
  • 资源
    资源Overview
    • 工具38 款浏览器内开发工具
    • 链接每日使用的开发与设计书签
  • 关于
  • 联系
EN

同步 · dev.to / @markyu

☕Understanding `final`, `finally`, and `finalize` in Java

Java programming involves a myriad of keywords, each serving distinct purposes to enhance the...

发布日期
May 24 '24
·
阅读时长
3 min read
·
点赞
13
·
评论数
3
javalearningkeywordsbeginners
在 dev.to 查看评论

Java programming involves a myriad of keywords, each serving distinct purposes to enhance the functionality and robustness of the code. Among these, final, finally, and finalize often cause confusion due to their similar nomenclature. However, they serve entirely different purposes. This article will elucidate the differences between these keywords, their uses, and practical examples to clarify their roles in Java programming.

Image description

Introduction

In Java, final, finally, and finalize are keywords with distinct functions:

  • final: A keyword used in variable, method, and class declarations to denote constants, prevent method overriding, and inheritance.
  • finally: A block used in exception handling to execute code regardless of whether an exception is thrown or not.
  • finalize: A method used to perform cleanup operations before an object is garbage collected.

Understanding the differences and applications of these keywords is crucial for writing effective Java code.

The final Keyword

Purpose

The final keyword is versatile and can be applied to variables, methods, and classes.

Use Cases

  1. Final Variables: When applied to a variable, the final keyword makes it a constant, meaning its value cannot be changed once assigned.
  2. Final Methods: When applied to a method, it prevents the method from being overridden by subclasses.
  3. Final Classes: When applied to a class, it prevents the class from being subclassed.

Code Examples

Final Variables

public class Constants {
    public static final int MAX_USERS = 100;
    public static final String APP_NAME = "MyApp";
}

In this example, MAX_USERS and APP_NAME are constants that cannot be changed.

Final Methods

public class Parent {
    public final void display() {
        System.out.println("This is a final method.");
    }
}

public class Child extends Parent {
    // This will cause a compile-time error
    // public void display() {
    //    System.out.println("Attempting to override a final method.");
    // }
}

Here, the display method in the Parent class cannot be overridden by the Child class.

Final Classes

public final class Utility {
    public static void performTask() {
        System.out.println("Performing a task.");
    }
}

// This will cause a compile-time error
// public class AdvancedUtility extends Utility {
// }

The Utility class cannot be subclassed due to the final keyword.

The finally Block

Purpose

The finally block is used in exception handling to execute code that must run regardless of whether an exception is thrown or caught.

Use Cases

  1. Resource Management: Ensuring resources like files and database connections are closed properly.
  2. Cleanup Operations: Performing necessary cleanup actions after try-catch blocks.

Code Example

public class FileOperations {
    public void readFile(String filePath) {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(filePath);
            // Perform file operations
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    System.out.println("Failed to close the file: " + e.getMessage());
                }
            }
        }
    }
}

In this example, the finally block ensures that the FileReader resource is closed regardless of whether an exception occurs.

The finalize Method

Purpose

The finalize method is invoked by the garbage collector before an object is reclaimed. It is used to perform cleanup operations, such as releasing resources.

Use Cases

  1. Cleanup Operations: Performing cleanup before an object is garbage collected.

Code Example

public class ResourceHolder {
    private FileReader fileReader;

    public ResourceHolder(String filePath) throws FileNotFoundException {
        this.fileReader = new FileReader(filePath);
    }

    @Override
    protected void finalize() throws Throwable {
        try {
            if (fileReader != null) {
                fileReader.close();
            }
        } finally {
            super.finalize();
        }
    }
}

Here, the finalize method ensures that the FileReader is closed before the ResourceHolder object is garbage collected. However, it's important to note that the finalize method is deprecated in recent Java versions due to unpredictability and better alternatives like try-with-resources and explicit resource management.

Summary

In summary, final, finally, and finalize are three distinct keywords in Java with different purposes:

  • final: Used to declare constants, prevent method overriding, and inheritance.
  • finally: A block used in exception handling to execute necessary code regardless of exceptions.
  • finalize: A method used for cleanup operations before an object is garbage collected (now largely deprecated).

Understanding these keywords helps in writing more robust, maintainable, and efficient Java code. By using final, you can create immutable variables and secure methods and classes. The finally block ensures resource management and cleanup, while finalize (despite its deprecation) shows the historical approach to object cleanup before garbage collection.


References:

  • Oracle Java Documentation
  • GeeksforGeeks - Java final, finally and finalize
  • Baeldung - Java Keywords

相关阅读

java

Understanding the `throw` and `throws` Keywords in Java

Exception handling is a crucial aspect of Java programming, allowing developers to manage and respond...

java

Advanced Java: Simplifying Object Property Copy and Manipulation with BeanUtil

In Java programming, the BeanUtil utility class is a powerful and convenient tool for simplifying the...

database

The True Cost of Poor Data Quality: Why It Matters and How to Improve It

In today’s fast-paced, data-driven world, businesses have more access to data than ever before....

原文发布

本文首发于 dev.to,评论与点赞保留在原站。

在 dev.to 继续阅读
上一篇Understanding the `throw` and `throws` Keywords in JavaException handling is a crucial aspect of Java programming, allowing developers to manage and respond...
返回档案
下一篇Key Considerations for Effective Database Table DesignIntroduction In database design, the structure of tables is a critical element that...
返回档案
频道开放·随时打个招呼 · 2026
--:--:--EST
联系

看到什么有意思的?和我聊聊。

这是一个作品集,不是服务 · 但每一条留言我都会看 — 如果哪里让你有所触动,或者只想打个招呼,欢迎写信过来。

开启对话

订阅

偶尔收到一封简讯

来自 m4rkyu.com 的笔记与日志——简短、标注日期、没有杂音。随时可退订。

作品

线上发布、游戏作品与视觉档案。

  • 项目
  • 游戏
  • 档案
  • 日志

资源

每日好用的工具与个人收藏的链接库。

  • 搜索
  • 最新
  • 工具
  • 链接
  • 笔记
  • 主题
  • RSS
  • JSON Feed
  • 商店

工作室

背景、联系方式以及合作渠道。

  • 关于
  • 联系
  • 更新日志
  • 技术说明
  • 简历筹备中

社交

在常去的平台上找到我。

  • Facebook敬请期待
  • Instagram敬请期待
  • YouTube敬请期待
  • 领英敬请期待
M4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYUM4RKYU
始于 2024
ZhenXiao Mark YuZhenXiao Mark Yu
© 2026 ZhenXiao Mark Yu·加拿大 安大略
  • 邮件
  • GitHub
  • dev.to
  • 领英 (敬请期待)
  • 推特 / X (敬请期待)
  • Instagram (敬请期待)
由 Next.js 16 · React 19 · Tailwind 4 构建

由 Next.js 16 · React 19 · Tailwind 4 构建