BhauAutomation

Java Collection Class and Final, Finally, Finalize

Understand the Java Collection framework and the difference between Final, Finally, and Finalize keywords. These are essential concepts in Java programming for code organization, exception handling, and memory management.

📘 Topic: Core Java / Collections
Read time: 7 min
📊 Level: Intermediate
🎯 Focus: Collections + Keywords
📚 Collections Framework

What is Collection Framework in Java?

The Collection Framework in Java provides a set of classes and interfaces to store and manipulate a group of objects efficiently. It is part of the java.util package and provides ready-made architecture for storing and processing data.

🎯 Objectives of Collection Framework

  • To represent a group of objects as a single unit
  • To provide ready-made data structures like List, Set, and Map
  • To improve code reusability and performance
  • To provide standard methods for data manipulation (add, remove, search, sort)
  • To reduce programming effort by offering efficient implementations

✅ Advantages of Collection Framework

  • Reduces development time with reusable data structures
  • Provides dynamic storage (no fixed size like arrays)
  • Supports algorithms like sorting, searching, and shuffling easily
  • Allows interoperability between different collection types
  • Thread-safe implementations available (Vector, Hashtable)

📊 Collection Framework Hierarchy

Iterable (Interface)
    │
    └── Collection (Interface)
            │
            ├── List (Interface) → ArrayList, LinkedList, Vector, Stack
            │
            ├── Set (Interface) → HashSet, LinkedHashSet, TreeSet
            │
            └── Queue (Interface) → PriorityQueue, ArrayDeque

Map (Interface) - Not part of Collection interface
    ├── HashMap, LinkedHashMap, TreeMap
    └── Hashtable

🔧 Common Interfaces and Classes

  • List Interface: ArrayList, LinkedList, Vector, Stack (ordered, allows duplicates)
  • Set Interface: HashSet, LinkedHashSet, TreeSet (unordered, no duplicates)
  • Queue Interface: PriorityQueue, ArrayDeque (FIFO order)
  • Map Interface: HashMap, TreeMap, LinkedHashMap (key-value pairs)

📝 Example – Using ArrayList

import java.util.*;

public class CollectionExample {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<String> courses = new ArrayList<>();
        
        // Adding elements
        courses.add("Selenium");
        courses.add("Java");
        courses.add("Appium");
        courses.add("API Testing");
        
        // Accessing elements
        System.out.println("All Courses: " + courses);
        System.out.println("First Course: " + courses.get(0));
        
        // Removing an element
        courses.remove("Appium");
        System.out.println("After removal: " + courses);
        
        // Iterating using for-each loop
        for (String course : courses) {
            System.out.println("Course: " + course);
        }
    }
}
🔑 Keywords Explained

Final, Finally, and Finalize in Java

These three keywords look similar but serve completely different purposes in Java. Understanding the difference between them is crucial for both coding and interviews.

🔒 final Keyword

Used to declare constants, prevent inheritance, or stop method overriding. The value of a final variable cannot be changed once assigned.

// final variable
final int MAX_VALUE = 100;

// final method (cannot override)
final void display() { }

// final class (cannot inherit)
final class Test { }

✅ finally Block

Used in exception handling to execute important code whether exception occurs or not. Always executes after try/catch blocks.

try {
    int data = 50 / 0;
} catch (ArithmeticException e) {
    System.out.println(e);
} finally {
    System.out.println("Cleanup code - Always executes");
}

🗑️ finalize() Method

Called by the garbage collector before destroying an object. Used to perform cleanup operations like closing resources.

protected void finalize() {
    System.out.println("Object destroyed");
    // Close resources here
}

⚡ Differences Between Final, Finally, and Finalize

Keyword/Method Usage/Purpose Belongs To When Used
final Makes variable constant, prevents method overriding & inheritance Variable, Method, Class Compile-time
finally Executes cleanup code regardless of exception Exception Handling Runtime (always executes)
finalize() Called before garbage collection for cleanup Object Class Before garbage collection}

🏆 Best Practices

Use final for constants and immutable values

Always close resources (files, DB connections) in finally block

Avoid relying on finalize(); use try-with-resources for Java 7+

Make utility classes final with private constructors

Use finally for guaranteed resource cleanup

Use final parameters for better code safety

📝 Complete Example – Final, Finally, Finalize

public class FinalFinallyFinalizeDemo {
    
    // final variable - cannot be changed
    final int MAX_ATTEMPTS = 3;
    
    // final method - cannot be overridden
    final void showMessage() {
        System.out.println("Learning Java Concepts!");
    }
    
    // finalize method - called before garbage collection
    protected void finalize() {
        System.out.println("Cleanup before object removal");
    }
    
    public static void main(String[] args) {
        try {
            int result = 10 / 2; // No exception
            System.out.println("Result: " + result);
        } catch (Exception e) {
            System.out.println("Exception caught");
        } finally {
            System.out.println("finally block always executes");
        }
        
        FinalFinallyFinalizeDemo obj = new FinalFinallyFinalizeDemo();
        obj.showMessage();
        System.out.println("Max attempts: " + obj.MAX_ATTEMPTS);
        
        obj = null;
        System.gc(); // Request garbage collection
    }
}