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 and memory management.

What is Collection Class 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.

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.

Advantages

• Reduces development time with reusable data structures.
• Provides dynamic storage (no fixed size like arrays).
• Supports algorithms like sorting and searching easily.

Common Interfaces and Classes

List Interface: ArrayList, LinkedList, Vector
Set Interface: HashSet, LinkedHashSet, TreeSet
Map Interface: HashMap, TreeMap, LinkedHashMap

Example – Using ArrayList


import java.util.*;

public class Example {
  public static void main(String[] args) {
    ArrayList list = new ArrayList<>();
    list.add("Java");
    list.add("Python");
    list.add("C++");
    System.out.println(list);
  }
}
    

Final, Finally, and Finalize in Java

These three keywords look similar but serve completely different purposes in Java:

Final

Used to declare constants, prevent inheritance, or stop method overriding.

final int MAX = 100;

Finally

Used in exception handling to execute important code whether exception occurs or not.


try {
  int data = 50 / 0;
} catch (Exception e) {
  System.out.println(e);
} finally {
  System.out.println("Finally block executed");
}
      

Finalize

Used to perform cleanup operations before garbage collection.


protected void finalize() {
  System.out.println("Finalize called before object deletion");
}
      

Differences Between Final, Finally, and Finalize

KeywordUsageBelongs To
finalConstant / Prevent inheritanceVariable, Method, Class
finallyUsed for cleanup codeException Handling
finalizeCalled before object destructionObject Class

Best Practices

• Use Final keyword for constants and security.
• Always close resources in Finally block.
• Avoid relying on Finalize; use try-with-resources instead.